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() << " ";
19 }
20 return 0;
21 }
原文地址:https://www.cnblogs.com/lidabo/p/3905830.html