这个类可以解析和操作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; }输出
<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; }
原文:http://blog.csdn.net/calmreason/article/details/20908551