標籤:
當使用xml_parser進行讀xml時,如果遇到中文字元會出現解析錯誤。
網上有解決方案說使用wptree來實現,但當使用wptree來寫xml時也會出錯。而使用ptree來寫中文時不會出錯。
綜合以上資訊,嘗試使用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>
定義結構體:
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:
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,需轉換成string
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函數:
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 }
boost.xml_parser中文字元問題 (轉)