2011-03-13 36 views

回答

11

繼承人一些代碼,爲我的作品...

// Create an empty property tree object 
ptree xmlTree; 

// Read the XML config string into the property tree. Catch any exception 
try { 
    stringstream ss; ss << xmlConfigString; 
    read_xml(ss, xmlTree); 
} 
catch (xml_parser_error &e) { 
    LOGERROR ("Failed to read config xml " << e.what()); 
} 
catch (...) { 
    LOGERROR ("Failed to read config xml with unknown error"); 
} 
4

其他的答案是不理想的,因爲使用istringstream不必要拷貝整個緩衝區。

this question的答案表明,你可以使用過時istrstream,但因爲這會產生警告,並可能在將來被刪除,一個更好的解決方案是使用boost::iostreams

boost::iostreams::stream<boost::iostreams::array_source> stream(moo.c_str(), moo.size()); 
boost::property_tree::read_json(stream, tree); 

這避免了不必要的複製緩衝區的方式與istrstream的方法相同(如果輸入緩衝區很大,這可能是一個相當大的問題),並且不必編寫自己的流類。

相關問題