boost ptree操作XML,方便又好用

 Boost ptree

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

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

例如:

读取固定路径下单一值

获取文本内容:pt.get<string>("confi.theme");//<theme>this is the result</theme>

获取当前节点的文本内容:pt.get<string>();//<theme>this is the result</theme>,当且仅当当前节点时theme

获取注释内容:pt.get<string("conf.<xmlcomment>");//<conf><!-- this is the result --></conf>

获取属性内容:pt.get<long>("conf.theme.<xmlattr>.id");//<theme id="123456"></theme>,id is 123456

配置文件

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <root>  
  2.     <students>  
  3.         <name>zhang san</name>  
  4.         <age>23</age>  
  5.     </students>  
  6. </root>  

代码
  1. #include <boost/property_tree/ptree.hpp>  
  2. #include <boost/property_tree/xml_parser.hpp>  
  3. #include <iostream>  
  4.   
  5. using namespace std;  
  6. using namespace boost::property_tree;  
  7.   
  8. int main()  
  9. {  
  10.     ptree pt;  
  11.     //open xml and read information to pt  
  12.     read_xml("conf.xml", pt);  
  13.     //read value to val need a path   
  14.     string name = pt.get<string>("root.students.name");  
  15.     cout<<"name:"<<name<<endl;  
  16.     int age =pt.get<int>("root.students.age");  
  17.     cout<<"age:"<<age<<endl;  
  18.     return 0;  
  19. }  
输出
name:zhang san
age:23
请按任意键继续. . .

遍历单层孩子

当迭代器遍历到一个既不是属性节点<xmlattr>也不是一个注释节点<xmlcomment>的时候,此时就是一个子节点,子节点的操作就可以按照:“读取固定路径下单一值”来操作。

遍历孩子使用:auto child = pt.get_child("conf.urls");//获取urls的孩子节点,这里的孩子既包括urls的属性,也包括urls的注释、也包括urls里面的多个子节点<url>www.baidu.com</url><url>www.sina.com</url>,当孩子是一个url节点的时候,迭代器的first是节点的名字url,second是ptree结构,可以继续使用get<type>()方法获取url的属性值,注释值,文本值,或者是子孩子的值。
配置文件
[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:14px;"><root>  
  2.     <students>  
  3.         <name>张三</name>  
  4.         <name>李四</name>  
  5.     <name>王二</name>  
  6.     </students>  
  7. </root></span>  
源代码
  1. <span style="font-size:14px;">#include <boost/property_tree/ptree.hpp>  
  2. #include <boost/property_tree/xml_parser.hpp>  
  3. #include <iostream>  
  4.   
  5. using namespace std;  
  6. using namespace boost::property_tree;  
  7.   
  8. int main()  
  9. {  
  10.     ptree pt;  
  11.     //open xml and read information to pt  
  12.     read_xml("conf.xml", pt);  
  13.     //iter all child value  
  14.     auto child = pt.get_child("root.students");  
  15.     for (auto i = child.begin();i!=child.end();++i)  
  16.     {  
  17.         string name = i->second.get_value<string>();//此时i->first的值为路径名:name  
  18.         cout<<name<<endl;  
  19.     }  
  20.       
  21.     return 0;  
  22. }</span>  
输出

张三
李四
王二
请按任意键继续. . .

遍历包含属性的孩子

配置文件
[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <root>  
  2.     <student name="张三" age="22">first student</student>  
  3.     <student name="李四" age="23">second student</student>  
  4.     <student name="王二" age="24">third student</student>  
  5. </root>  

源代码
  1. #include <boost/property_tree/ptree.hpp>  
  2. #include <boost/property_tree/xml_parser.hpp>  
  3. #include <iostream>  
  4.   
  5. using namespace std;  
  6. using namespace boost::property_tree;  
  7.   
  8. int main()  
  9. {  
  10.     ptree pt;  
  11.     //open xml and read information to pt  
  12.     read_xml("conf.xml", pt);  
  13.     //iter all child value  
  14.     auto child = pt.get_child("root");  
  15.     for (auto i = child.begin();i!=child.end();++i)  
  16.     {  
  17.         string stu= i->second.get<string>("");  
  18.         cout<<"student:"<<stu<<endl;  
  19.         string  name = i->second.get<string>("<xmlattr>.name");  
  20.         cout<<"name:"<<name<<endl;  
  21.         string  age = i->second.get<string>("<xmlattr>.age");  
  22.         cout<<"age:"<<age<<endl;  
  23.     }  
  24.     return 0;  
  25. }  


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

嵌套遍历

转自:http://www.verydemo.com/demo_c441_i198847.html

摘要:

property_tree是一个保存了多个属性值的属性数据结构,可以用类似路径的简单方式访问任意节点的属性,而且每个节点都可以用类似STL的风格遍历子节点。property_tree特别适合于应用程序的配置数据处理,可以解析xml、ini、json和info四个格式的文本数据。

在处理四种格式的文件时,除包含头文件、读文件、写文件时有部分区别外,其他对文件内部数据操作时基本一致(因为文件格式都基本一直)。实际上,property_tree内部使用的就是一个小巧快速的开源XML解析器——rapidxml。


使用方法:

1)不同:(XXX分别代码xml、json、ini、info)

  1. #include <boost/property_tree/ptree.hpp>  
  2. #include <boost/property_tree/XXX_parser.hpp>  
  3. using namespace boost::property_tree;   
  4. void main(void)   
  5. {   
  6.     ptree pt;   
  7.     read_XXX("./test.XXX", pt); // 读文件  
  8.     // ....其他操作   
  9.     write_XXX(cout, pt);        // 写文件,有两种格式:  
  10.                     // void write_XXX(const string &, Ptree &pt);  
  11.                     // void write_XXX(basic_ostream &, Ptree &pt);  
  12. }  
  1. #include <boost/property_tree/ptree.hpp>  
  2. #include <boost/property_tree/XXX_parser.hpp>  
  3. using namespace boost::property_tree;  
  4. void main(void)  
  5. {  
  6.     ptree pt;  
  7.     read_XXX("./test.XXX", pt); // 读文件  
  8.     // ....其他操作  
  9.     write_XXX(cout, pt);        // 写文件,有两种格式:  
  10.                     // void write_XXX(const string &, Ptree &pt);  
  11.                     // void write_XXX(basic_ostream &, Ptree &pt);  
  12. }  


2)相同:(下面以xml为基础详细介绍,其他三种类型没测试过,囧~)

测试的XML文件:test.xml

  1.  

    [html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
    1. <?xml version="1.0" encoding="utf-8"?>  
    2.   
    3. <config>   
    4.   <file title="windows" size="10Mb">   
    5.     <!-- File Fisrt Comment -->    
    6.     <!-- File Second Comment -->    
    7.     <paths attr="directory1">   
    8.       <!-- Paths Comment -->    
    9.       <pathname title="123">abc</pathname>    
    10.       <pathname title="456">efg</pathname>    
    11.       <pathname title="789">hij</pathname>   
    12.     </paths>    
    13.     <paths attr="directory2">   
    14.       <pathname title="111">klm<!-- pathname Comment -->    
    15.       </pathname>    
    16.       <pathname title="222">nop</pathname>    
    17.       <pathname title="333">qrs</pathname>   
    18.     </paths>   
    19.   </file>   
    20. </config>  

    测试代码:

  1. #include <iostream>  
  2. #include <string>  
  3. #include <boost/typeof/typeof.hpp>  
  4. #include <boost/property_tree/ptree.hpp>  
  5. #include <boost/property_tree/xml_parser.hpp>  
  6.   
  7. using namespace std;  
  8. using namespace boost::property_tree;  
  9.   
  10. int main(void)  
  11. {  
  12.     char szXmlFile[] = "./test.xml";  
  13.   
  14.     string strTmp;  
  15.   
  16.     ptree pt;  
  17.     xml_parser::read_xml(szXmlFile, pt);  
  18.   
  19.     BOOST_AUTO(file_childs, pt.get_child("config.file"));  
  20.     //serch(child,0);  
  21.     for (BOOST_AUTO(file_childs_iter, file_childs.begin()); file_childs_iter != file_childs.end(); ++file_childs_iter)//file  
  22.     {  
  23.         strTmp.clear();  
  24.         if ("<xmlattr>" == file_childs_iter->first)  
  25.         {  
  26.             //此节点的first是xmlattr,second节点时pair,按照key,value来取值,key是路径  
  27.             strTmp = file_childs_iter->second.get<string>("title");        // 输出:windows  
  28.             cout<<file_childs_iter->first<<",  title: "<<strTmp<<"\n";  
  29.   
  30.             strTmp = file_childs_iter->second.get<string>("size");     // 输出:10Mb  
  31.             cout<<file_childs_iter->first<<",  size: "<<strTmp<<"\n";  
  32.   
  33.             strTmp = file_childs_iter->second.get<string>("not exits""This is default");   
  34.             cout<<file_childs_iter->first<<",  not exist:"<<strTmp<<endl;  // 输出:This is default  
  35.         }  
  36.         else if ("<xmlcomment>" == file_childs_iter->first)  
  37.         {  
  38.             strTmp = file_childs_iter->second.get_value<string>();     // 第一次输出:File First Comment  
  39.             cout<<file_childs_iter->first<<",  comment: "<<strTmp<<"\n";     // 第二次输出:File Second Comment  
  40.         }  
  41.         else//paths  
  42.         {  
  43.             BOOST_AUTO(paths_childs, file_childs_iter->second.get_child(""));  
  44.             for (BOOST_AUTO(paths_childs_iter, paths_childs.begin()); paths_childs_iter != paths_childs.end(); ++paths_childs_iter)//paths  
  45.             {  
  46.                 strTmp.clear();  
  47.                 if ("<xmlattr>" == paths_childs_iter->first)  
  48.                 {  
  49.                     cout<<file_childs_iter->first<<" ";  
  50.                     //此节点的first是xmlattr,second节点时pair,按照key,value来取值,key是路径  
  51.                     strTmp = paths_childs_iter->second.get<string>("attr");  
  52.                     cout<<paths_childs_iter->first<<",  attr: "<<strTmp<<"\n";  
  53.                 }  
  54.                 else if ("<xmlcomment>" == paths_childs_iter->first)  
  55.                 {  
  56.                     cout<<file_childs_iter->first<<" ";  
  57.                     strTmp = paths_childs_iter->second.get_value<string>();          
  58.                     cout<<paths_childs_iter->first<<",  comment: "<<strTmp<<"\n";      
  59.                 }  
  60.                 else//pathname  
  61.                 {  
  62.                         cout<<file_childs_iter->first<<" ";  
  63.                         strTmp = paths_childs_iter->second.get<string>("<xmlattr>.title");         
  64.                         cout<<paths_childs_iter->first<<"  title: "<<strTmp<<" content:" <<paths_childs_iter->second.data()<<"\n";      
  65.                 }  
  66.             }  
  67.         }  
  68.   
  69.     }  
  70.     cin.get();  
  71.     return 0;  
  72. }  

 
测试结果:



分析:从上述测试中可以看出,BOOST封装的RapidXml开源库,是将XML文件内容解析为一个树状结构。比如说本例中使用的节点“config.file”,具有五个子节点:一个属性子节点、两个注释子节点、两个数据子节点,且顺序为属性→注释→数据
①属性子节点:
每个节点只有一个属性子节点,是一对多关系,即一个属性子节点对应多个属性!
"if ("<xmlattr>" == pos->first)",然后获取属性的值则为“pos->second.get<string>("title")”和“pos->second.get<string>("size")”。注意这里获取属性,不再是"<xmlattr>.title",因为此时pos已经指向本节点,不再需要用"<xmlattr>"递推到属性子节点!
②注释子节点:节点可以有多个属性子节点,是一对一关系!!!
”if ("<xmlcomment>" == pos->first)“,获取属性则“pos->second.data()”;或者iter->second.get_value<string>()
③数据子节点:这种节点又可以重新看做是一个节点,下面会对应属性子节点、注释子节点、数据子节点。但注意“pos->second.get_child("")”是返回当前节点的所有子节点(包含属性、注释、数据),而“pt.get_child("config.file")“是返回file节点下所有节点(包含属性、注释、数据)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值