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

來源:互聯網
上載者:User

標籤:

當使用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中文字元問題 (轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.