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);

}

原博客链接:http://blog.csdn.net/zshtang/article/details/6664164

posted on 2013-08-07 11:33  liygcheng  阅读(824)  评论(0编辑  收藏  举报

导航