boost 解析 xml 文件

xml_parser

[ 经试验证明,boost 库中xml 解析库对中文支持不好,解析出来是乱码 ]

头文件:

#include<boost/property_tree/ptree.hpp>

#include<boost/property_tree/xml_parser.hpp>

 

命名空间:

using namespaceboost::property_tree;

 

读入xml 文件:

xml文件内容被读入ptree 对象中,然后进行解析

ptree pt;

read_xml(“xml_file_name”, pt);

 

tips:

voidread_xml(const string&,  ptree&pt);

voidread_xml(const string&,  ptree&pt);

 

获取xml 文件内容

pt.get<type>(tag,  default_value); // type = {string,  int, long}

pt.get<string>(tag);

pt.get<int>(tag);

pt.get<long>(tag);

tag 是直接的一级节点的标签如“document“ ; 或者二级标签 “document.English“

或者tag的属性的标签

“document.English.<xmlattr>.name“

“document.English.<xmlattr>.value“

 

tag之获取注释内容

“document.<xmlcomment>“

 

<document>

       <!-- [ comments ] -->

    <English name="name"value="value">The world has many languages</English>

    <Russian name="имя"value="значение">В мире множество языков</Russian>

    <Spanish name="el nombre"value="el valor">el mundo tiene muchos idiomas</Spanish>

    <SimplifiedChinese name="名字" value="价值">世界有很多语言</SimplifiedChinese>

    <Русский имя="name"значение="value">&lt;Мир&gt;</Русский>

    <汉语名字="name" 价值="value">世界有很多语言</汉语>

   <Heavy>"M&#x065;t&#065;l!"</Heavy>

    <a>Umlaut Element</a>

</document>

 

对于有多个子节点的对象

BOOST_AUTO(child,  pt.get_child(“DataDictionary”))

for(BOOST_AUTO(pos,  child.begin());  pos != child.end();  ++pos )

{

       cout<< pos->second.data() << endl;

}

 

<DataDictionary>

  <DataField name="prov"optype="categorical" dataType="double" >1</DataField>

  <DataField name="urb"optype="categorical" dataType="double" >2</DataField>

  <DataField name="ses"optype="categorical" dataType="double" >3</DataField>

</DataDictionary>

 

写xml 文件:

voidwrite_xml(const string &,  ptree& pt);

voidwrite_xml(basic_ostream &,  ptree& pt);

 

添加节点

pt.put(tag, value); // tag = “document.English” value = “The world has many languages”

 

添加子节点

pt.add(tag, value);

 

#include<boost/property_tree/ptree.hpp>

#include <boost/property_tree/xml_parser.hpp>

int main()

{

       usingnamespace boost::property_tree;

      

       ptreept;

       read_xml(“xml_file_name”,  pt);

       pt.put(“document.English”,  “The world has many languages”);

       pt.put(“document.Spanish”,  “el mundo tiene muchos idiomas”);

      

       write_xml(“new_xml_name”,  pt);

       write_xml(cout,  pt);

}

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值