首页 > 其他 > 详细

ptree

时间:2014-03-10 19:52:16      阅读:545      评论:0      收藏:0      [点我收藏+]

这个类可以解析和操作xml文件。下面的程序就列举和展示ptree类对xml文件的常用操作。

get<type>(path) 获取路径上的节点的属性或者文本内容等

pt.get_child("root")  路径指定节点的文本内容

string stu= i->second.get<string>(""); 获取当前节点的文本内容

string  name = i->second.get<string>("<xmlattr>.name"); 获取当前节点的属性值

  • 读取单个值

配置文件

<root>
    <students>
        <name>zhang san</name>
        <age>23</age>
    </students>
</root>

代码
#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 pt
	read_xml("conf.xml", pt);
	//read value to val need a path 
	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;
}
输出
name:zhang san
age:23
请按任意键继续. . .


  • 遍历孩子
配置文件
<root>
    <students>
        <name>张三</name>
        <name>李四</name>
	<name>王二</name>
    </students>
</root>
源代码
#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 pt
	read_xml("conf.xml", pt);
	//iter all child value
	auto child = pt.get_child("root.students");
	for (auto i = child.begin();i!=child.end();++i)
	{
		string name = i->second.get_value<string>();
		cout<<name<<endl;
	}
	
	return 0;
}
输出

张三
李四
王二
请按任意键继续. . .
  • 遍历包含属性的孩子
配置文件
<root>
    <student name="张三" age="22">first student</student>
    <student name="李四" age="23">second student</student>
    <student name="王二" age="24">third student</student>
</root>

源代码
#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 pt
	read_xml("conf.xml", pt);
	//iter all child value
	auto child = pt.get_child("root");
	for (auto i = child.begin();i!=child.end();++i)
	{
		string stu= i->second.get<string>("");
		cout<<"student:"<<stu<<endl;
		string  name = i->second.get<string>("<xmlattr>.name");
		cout<<"name:"<<name<<endl;
		string  age = i->second.get<string>("<xmlattr>.age");
		cout<<"age:"<<age<<endl;
	}
	return 0;
}


输出
student:first student
name:张三
age:22
student:second student
name:李四
age:23
student:third student
name:王二
age:24
请按任意键继续. . .

  • 修改单个值

  • 添加子节点

ptree,布布扣,bubuko.com

ptree

原文:http://blog.csdn.net/calmreason/article/details/20908551

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!