boost.xml_parser中文字符問題 (轉)

當使用xml_parser進行讀xml時,若是遇到中文字符會出現解析錯誤。ios

網上有解決方案說使用wptree來實現,但當使用wptree來寫xml時也會出錯。而使用ptree來寫中文時不會出錯。json

 

綜合以上信息,嘗試使用ptree來寫xml,而用wptree來讀。以一個demo來講明吧。函數

複製代碼
1 //包含文件 2 #include <boost/property_tree/ptree.hpp> 3 #include <boost/property_tree/xml_parser.hpp> 4 #include <boost/property_tree/json_parser.hpp> 5 #include <boost/foreach.hpp> 6 #include <string> 7 #include <exception> 8 #include <iostream>
複製代碼

 

定義結構體:this

複製代碼
1 struct debug_simple 2 { 3 int itsNumber; 4 std::string itsName; //這裏使用string就能夠 5 void load(const std::string& filename); //載入函數 6 void save(const std::string& filename); //保存函數 7 };
複製代碼

保存函數,使用ptree:spa

複製代碼
 1 void debug_simple::save( const std::string& filename )  2 {  3 using boost::property_tree::ptree;  4 ptree pt;  5  6 pt.put("debug.number",itsNumber);  7 pt.put("debug.name",itsName);  8  9 write_xml(filename,pt); 10 }
複製代碼

 

載入函數使用的wptree,讀取的值爲wstring,需轉換成stringdebug

複製代碼
 1 void debug_simple::load( const std::string& filename )  2 {  3 using boost::property_tree::wptree;  4 wptree wpt;  5 read_xml(filename, wpt);  6  7 itsNumber = wpt.get<int>(L"debug.number");  8 std::wstring wStr = wpt.get<std::wstring>(L"debug.name");  9 itsName = std::string(wStr.begin(),wStr.end()); //wstring轉string 10 }
複製代碼

main函數:code

複製代碼
 1 int _tmain(int argc, _TCHAR* argv[])  2 {  3  4 try  5 {  6 debug_simple ds,read;  7 ds.itsName = "漢字english";  8 ds.itsNumber = 20;  9 10 ds.save("simple.xml"); 11 read.load("simple.xml"); 12 13 std::cout<<read.itsNumber<<read.itsName; 14 15 } 16 catch (std::exception &e) 17 { 18 std::cout << "Error: " << e.what() << "\n"; 19 } 20 return 0; 21 }
複製代碼
相關文章
相關標籤/搜索