boost::property_tree 基本用法

来源:互联网 发布:双色球算法必中6红组合 编辑:程序博客网 时间:2024/05/16 17:53

    最近在开发C++时需要解析和设置配置文件XML,用了boost::property_tree ,看了相关资料并做了一下小小的总结:

1.读取单个值

XML:

<root>    <students>        <name>zhang san</name>        <age>23</age>    </students></root>
C++代码:

#include <boost/property_tree/ptree.hpp>#include <boost/property_tree/xml_parser.hpp>#include <iostream>using namespace std;using namespace boost::property_tree;int main(){ptree pt;//open xml and read information to ptread_xml("conf.xml", pt);//直接利用点运算符进行读取string name = pt.get<string>("root.students.name");cout<<"name:"<<name<<endl;int age =pt.get<int>("root.students.age");cout<<"age:"<<age<<endl;return 0;}
2.遍历孩子
XML:
<pre code_snippet_id="227288" snippet_file_name="blog_20140310_3_6696140" name="code" class="html" style="margin-top: 0px; margin-bottom: 10px; font-weight: bold; line-height: 24.05px; background-color: rgb(255, 255, 255);"><root>    <students>        <name>张三</name>        <name>李四</name><name>王二</name>    </students></root>
C++源代码:

<pre code_snippet_id="227288" snippet_file_name="blog_20140310_4_1396223" name="code" class="cpp" style="margin-top: 0px; margin-bottom: 10px; font-weight: bold; line-height: 24.05px; background-color: rgb(255, 255, 255);">int main(){ptree pt;read_xml("conf.xml", pt);//获取students孩子进行遍历auto child = pt.get_child("root.students");for (auto i = child.begin();i!=child.end();++i){string name = i->second.get_value<string>();//注意使用i->second.get<string>()
cout<<name<<endl;}return 0;}
3.遍历包含孩子的属性
XML:
<root>  <students>        <student>      <student name="张三" age="22">first student</student>    </student>        <student>      <student name="李四" age="23">second student</student>    </student>  </students></root>
C++源代码:

int main()
{
ptree pt;
read_xml("E:/UIMRIS/BRANCHES/uMR_MAIN/MAIN/Features/win32test/XMLFile1.xml", pt);


auto child = pt.get_child("root.students");
for (auto i = child.begin();i!=child.end();++i)
{
auto student = i ->second.get_child(""); //不需要节点号,但引号必须有
for (auto j = student.begin(); j!= student.end(); ++j)
{
string stu= j->second.get<string>("");
cout<<"student:"<<stu<<endl;
string  name = j->second.get<string>("<xmlattr>.name");
cout<<"name:"<<name<<endl;
string  age = j->second.get<string>("<xmlattr>.age");
cout<<"age:"<<age<<endl;
}
}


getchar();
return 0;
}


0 0
原创粉丝点击