boost.xml_parser中文字符问题 (转)

当使用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 }
复制代码

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值