DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

当使用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 }
posted on   DoubleLi  阅读(616)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示