boost::property_tree

boost::property_tree 的解析xml模块是基于rapidXml的, 以下是两个例子:

例子1:

  1. #include <boost/property_tree/ptree.hpp> 
  2. #include <boost/property_tree/xml_parser.hpp> 
  3. #include <boost/typeof/typeof.hpp> 
  4. #include <iostream> 
  5.  
  6. using namespace std; 
  7.  
  8. void ReadConfig() 
  9.   boost::property_tree::ptree pt; 
  10.         boost::property_tree::read_xml("del.conf", pt); 
  11.         filenum = pt.get<int>("root.delfile.filenum"); 
  12.  
  13.         cout << "filenum: " << filenum << endl; 
  14.          
  15.         BOOST_AUTO(child, pt.get_child("root.delfile.paths")); 
  16.         for (BOOST_AUTO(pos, child.begin()); pos != child.end(); ++pos) 
  17.         { 
  18.          BOOST_AUTO(child_paths, pos->second.get_child("")); //此处不需要填结点名,但引号不能省. 
  19.          for (BOOST_AUTO(pos_paths, child_paths.begin()); pos_paths != child_paths.end(); ++pos_paths) 
  20.           cout << pos_paths->second.data() << endl; 
  21.         } 
  22.          
  23. int main() 
  24. ReadConfig(); 
  25. return 0; 
  26.  
  27.  
  28. /*
  29. 附录:配置文件del.conf
  30. */ 
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/typeof/typeof.hpp>
#include <iostream>

using namespace std;

void ReadConfig()
{
  boost::property_tree::ptree pt;
        boost::property_tree::read_xml("del.conf", pt);
        filenum = pt.get<int>("root.delfile.filenum");

        cout << "filenum: " << filenum << endl;
        
        BOOST_AUTO(child, pt.get_child("root.delfile.paths"));
        for (BOOST_AUTO(pos, child.begin()); pos != child.end(); ++pos)
        {
         BOOST_AUTO(child_paths, pos->second.get_child("")); //此处不需要填结点名,但引号不能省.
         for (BOOST_AUTO(pos_paths, child_paths.begin()); pos_paths != child_paths.end(); ++pos_paths)
          cout << pos_paths->second.data() << endl;
        }
        
}
int main()
{
 ReadConfig();
 return 0;
}


/*
附录:配置文件del.conf
*/

  1. <root> 
  2. <delfile> 
  3.  
  4.   <filenum> 35 </filenum> 
  5.  
  6.   <paths> 
  7.    <path>  
  8.     <pathname>/tmp/tmp0/</pathname> 
  9.     <before_hours> 0 </before_hours> 
  10.    </path> 
  11.    
  12.    <path>  
  13.     <pathname>/tmp/tmp1/</pathname> 
  14.     <before_hours> 1 </before_hours> 
  15.    </path> 
  16.    
  17.    <path>  
  18.     <pathname>/tmp/tmp2/</pathname> 
  19.     <before_hours> 2 </before_hours> 
  20.    </path> 
  21.    
  22.    <path>  
  23.     <pathname>/tmp/tmp3/</pathname> 
  24.     <before_hours> 3 </before_hours> 
  25.    </path> 
  26.    
  27.    <path>  
  28.     <pathname>/tmp/tmp4/</pathname> 
  29.     <before_hours> 4 </before_hours> 
  30.    </path> 
  31.   </paths> 
  32.  
  33. </delfile> 
  34.  
  35.  
  36. <backup> 
  37.   <backuptime> 23:59 </backuptime> 
  38. </backup> 
  39.  
  40. </root> 
<root>
 <delfile>

  <filenum> 35 </filenum>

  <paths>
   <path> 
    <pathname>/tmp/tmp0/</pathname>
    <before_hours> 0 </before_hours>
   </path>
  
   <path> 
    <pathname>/tmp/tmp1/</pathname>
    <before_hours> 1 </before_hours>
   </path>
  
   <path> 
    <pathname>/tmp/tmp2/</pathname>
    <before_hours> 2 </before_hours>
   </path>
  
   <path> 
    <pathname>/tmp/tmp3/</pathname>
    <before_hours> 3 </before_hours>
   </path>
  
   <path> 
    <pathname>/tmp/tmp4/</pathname>
    <before_hours> 4 </before_hours>
   </path>
  </paths>

 </delfile>


 <backup>
  <backuptime> 23:59 </backuptime>
 </backup>

</root>


例子2:

  1. #include <iostream> 
  2. #include <string> 
  3. #include <boost/property_tree/ptree.hpp> 
  4. #include <boost/property_tree/xml_parser.hpp> 
  5. #include <boost/foreach.hpp> 
  6.  
  7. using namespace std; 
  8. using namespace boost::property_tree; 
  9.  
  10. int main(void){ 
  11.     ptree pt; 
  12.     read_xml("debug_settings.xml", pt); 
  13.  
  14.         //loop for every node under debug 
  15.     BOOST_FOREACH(ptree::value_type &v1, pt.get_child("debug")){ 
  16.  
  17.         if(v1.first == "<xmlattr>"){ //it's an attribute 
  18.             //read debug name="debugname" 
  19.             cout<< "debug name=" << v1.second.get<string>("name") << endl; 
  20.         }else if(v1.first == "file"){ 
  21.             //read file name="debug.log" 
  22.             cout << "  file name=" << v1.second.get<string>("<xmlattr>.name") << endl; 
  23.         } 
  24.         else{ // v1.first == "modules" 
  25.             //get module type 
  26.             cout<< "  module type:" << v1.second.get<string>("<xmlattr>.type") << endl; 
  27.  
  28.             //loop for every node under modules 
  29.             BOOST_FOREACH(ptree::value_type &v2, v1.second){ 
  30.                 if(v2.first == "<xmlattr>"){  //it's an attribute 
  31.                     //this can also get module type 
  32.                     cout<< "  module type again:" << v2.second.get<string>("type") << endl; 
  33.                 } 
  34.                 else
  35.                     //all the modules have the same structure, so just use data() function. 
  36.                     cout<< "    module name:" << v2.second.data() << endl; 
  37.                 } 
  38.             }//end BOOST_FOREACH 
  39.         } 
  40.     }//end BOOST_FOREACH 
#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>

using namespace std;
using namespace boost::property_tree;

int main(void){
	ptree pt;
	read_xml("debug_settings.xml", pt);

        //loop for every node under debug
	BOOST_FOREACH(ptree::value_type &v1, pt.get_child("debug")){

		if(v1.first == "<xmlattr>"){ //it's an attribute
			//read debug name="debugname"
			cout<< "debug name=" << v1.second.get<string>("name") << endl;
		}else if(v1.first == "file"){
			//read file name="debug.log"
			cout << "  file name=" << v1.second.get<string>("<xmlattr>.name") << endl;
		}
		else{ // v1.first == "modules"
			//get module type
			cout<< "  module type:" << v1.second.get<string>("<xmlattr>.type") << endl;

			//loop for every node under modules
			BOOST_FOREACH(ptree::value_type &v2, v1.second){
				if(v2.first == "<xmlattr>"){  //it's an attribute
					//this can also get module type
					cout<< "  module type again:" << v2.second.get<string>("type") << endl;
				}
				else{
					//all the modules have the same structure, so just use data() function.
					cout<< "    module name:" << v2.second.data() << endl;
				}
			}//end BOOST_FOREACH
		}
	}//end BOOST_FOREACH
}



  1. <debug name="debugname">   
  2.     <file name="debug.log"/>   
  3.     <modules type="internal">   
  4.         <module1>Finance_Internal</module1>   
  5.         <module2>Admin_Internal</module2>   
  6.         <module3>HR_Internal</module3>   
  7.     </modules>   
  8.        
  9.     <modules type="external">   
  10.         <module>Finance_External</module>   
  11.         <module>Admin_External</module>   
  12.         <module>HR_External</module>     
  13.     </modules>   
  14. </debug>   
<debug name="debugname">  
    <file name="debug.log"/>  
    <modules type="internal">  
        <module1>Finance_Internal</module1>  
        <module2>Admin_Internal</module2>  
        <module3>HR_Internal</module3>  
    </modules>  
      
    <modules type="external">  
        <module>Finance_External</module>  
        <module>Admin_External</module>  
        <module>HR_External</module>    
    </modules>  
</debug>  



----------------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------------

关于boost::property_tree, 转自:  http://notes.xj-labs.net/?p=52


Boost.PropertyTree 应该是 Boost 1.41.0 开始正式加入 Boost 版本的。目前 ( 2010/02/28 ) 能下到的最新版本是 1.42.0。


  • 主要作用/应用场合

Boost.PropertyTree 提供了一种结构化的数据存储容器。并且提供了一系列的解释器可以将内存中的结构与具体格式相互转换 (比如: INI, XML, JSON )。

至少可以用在:

  1. 进程间通讯或者跨语言的进程间的通讯
  2. 一些配置文件的存取
  3. 网络通讯协议的格式

  • 基本用法

基本用法有 2 种场景。第一种是从 Property Tree存储到具体格式。第二种是从具体格式解析到具体的 Property Tree。其他还有一些 Property Tree 操作的方法,比如:遍历、搜索等方法。

以下这个 Sample 就是基本用法的测试:

先把 数据存储到 datum 中,随后输出 相应的 XML 和 JSON 到 std::cout 上。最后再从 JSON Stream 中解析输入到 ptParse 中获得相应 的数据。

  1. #include <stdio.h> 
  2.  
  3. #include <iostream> 
  4. #include <sstream> 
  5. #include <string> 
  6. #include <locale> 
  7.  
  8. #include "boost/property_tree/ptree.hpp" 
  9. #include "boost/property_tree/json_parser.hpp" 
  10. #include "boost/property_tree/xml_parser.hpp" 
  11.  
  12. int main(int argc, char **argv) 
  13.     /* The data format
  14.      * <root>
  15.      *  <num>1</num>
  16.      *  <str>Test</str>
  17.      * </root>
  18.      */ 
  19.     try 
  20.     { 
  21.         /* create the property tree */ 
  22.         boost::property_tree::ptree datum; 
  23.         datum.put("root.num", 100); 
  24.         datum.put("root.str", "string"); 
  25.  
  26.         /* output XML string */ 
  27.         std::ostringstream xmlOutputStream; 
  28.         boost::property_tree::xml_parser::write_xml(xmlOutputStream, 
  29.             datum); 
  30.         std::cout << "XML format:" << std::endl; 
  31.         std::cout << xmlOutputStream.str() << std::endl; 
  32.  
  33.         /* output JSON string */ 
  34.         std::ostringstream jsonOutputStream; 
  35.         boost::property_tree::json_parser::write_json(jsonOutputStream, 
  36.             datum); 
  37.         std::cout << "JSON format:" << std::endl; 
  38.         std::cout << jsonOutputStream.str() << std::endl; 
  39.  
  40.         /* read datum from JSON stream */ 
  41.         boost::property_tree::ptree ptParse; 
  42.         std::istringstream jsonIStream; 
  43.         jsonIStream.str(jsonOutputStream.str()); 
  44.         boost::property_tree::json_parser::read_json(jsonIStream, 
  45.             ptParse); 
  46.         int num = ptParse.get<int>("root.num"); 
  47.         std::string strVal = ptParse.get<std::string>("root.str"); 
  48.         std::cout << "Num=" << std::dec << num 
  49.             << " Str=" << strVal << std::endl << std::endl; 
  50.     } 
  51.     catch (...) 
  52.     { 
  53.         printf("create boost::property_tree::ptree failed\n"); 
  54.     } 
  55.  
  56.     return 0; 
#include <stdio.h>

#include <iostream>
#include <sstream>
#include <string>
#include <locale>

#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/json_parser.hpp"
#include "boost/property_tree/xml_parser.hpp"

int main(int argc, char **argv)
{
    /* The data format
     * <root>
     *  <num>1</num>
     *  <str>Test</str>
     * </root>
     */
    try
    {
        /* create the property tree */
        boost::property_tree::ptree datum;
        datum.put("root.num", 100);
        datum.put("root.str", "string");

        /* output XML string */
        std::ostringstream xmlOutputStream;
        boost::property_tree::xml_parser::write_xml(xmlOutputStream,
            datum);
        std::cout << "XML format:" << std::endl;
        std::cout << xmlOutputStream.str() << std::endl;

        /* output JSON string */
        std::ostringstream jsonOutputStream;
        boost::property_tree::json_parser::write_json(jsonOutputStream,
            datum);
        std::cout << "JSON format:" << std::endl;
        std::cout << jsonOutputStream.str() << std::endl;

        /* read datum from JSON stream */
        boost::property_tree::ptree ptParse;
        std::istringstream jsonIStream;
        jsonIStream.str(jsonOutputStream.str());
        boost::property_tree::json_parser::read_json(jsonIStream,
            ptParse);
        int num = ptParse.get<int>("root.num");
        std::string strVal = ptParse.get<std::string>("root.str");
        std::cout << "Num=" << std::dec << num
            << " Str=" << strVal << std::endl << std::endl;
    }
    catch (...)
    {
        printf("create boost::property_tree::ptree failed\n");
    }

    return 0;
}



  • 关于字符集

Boost 目前是支持 UTF8 的,但是不能用 直接用 Unicode。所以,如果要存储宽字符就有点麻烦需要用到 Boost 提供的 utf8_codecvt_facet 做转换。

下面就是一个存储 wchar_t 的 Sample:

和之前的其实差不多,有 2 点主要不同。一是用了 wptree 替换了 ptree。二是增加了 utf8_codecvt_facet 在相应的 Stream 里做转换。

  1. #include <stdio.h> 
  2.  
  3. #include <iostream> 
  4. #include <sstream> 
  5. #include <string> 
  6. #include <locale> 
  7.  
  8. #include "boost/property_tree/ptree.hpp" 
  9. #include "boost/property_tree/json_parser.hpp" 
  10. #include "boost/property_tree/xml_parser.hpp" 
  11.  
  12. #include "boost/program_options/detail/convert.hpp" 
  13. #include "boost/program_options/detail/utf8_codecvt_facet.hpp" 
  14.  
  15. int main(int argc, char **argv) 
  16.     /* The data format
  17.      * <root>
  18.      *  <num>1</num>
  19.      *  <str>Test</str>
  20.      * </root>
  21.      */ 
  22.     /* test UTF-8 format */ 
  23.     try 
  24.     { 
  25.         /* create boost utf8 codecvt */ 
  26.         std::locale oldLocale; 
  27.         std::locale utf8Locale(oldLocale, 
  28.             new boost::program_options::detail::utf8_codecvt_facet()); 
  29.         std::wcout.imbue(utf8Locale); 
  30.  
  31.         /* create the wptree for save the UTF-8 data */ 
  32.         boost::property_tree::wptree datum; 
  33.         datum.put(L"root.num", 100); 
  34.         datum.put(L"root.str", L"wstring"); 
  35.  
  36.         /* output XML string */ 
  37.         std::wostringstream xmlOutputStream; 
  38.         xmlOutputStream.imbue(utf8Locale); 
  39.         boost::property_tree::xml_parser::write_xml(xmlOutputStream, 
  40.             datum); 
  41.         std::wcout << L"XML format:" << std::endl; 
  42.         std::wcout << xmlOutputStream.str() << std::endl; 
  43.  
  44.         /* output JSON string */ 
  45.         std::wostringstream jsonOutputStream; 
  46.         jsonOutputStream.imbue(utf8Locale); 
  47.         boost::property_tree::json_parser::write_json(jsonOutputStream, 
  48.             datum); 
  49.         std::wcout << L"JSON format:" << std::endl; 
  50.         std::wcout << jsonOutputStream.str() << std::endl; 
  51.  
  52.         /* read datum from JSON stream */ 
  53.         boost::property_tree::wptree wptParse; 
  54.         std::wistringstream jsonIStream; 
  55.         jsonIStream.imbue(utf8Locale); 
  56.         jsonIStream.str(jsonOutputStream.str()); 
  57.         boost::property_tree::json_parser::read_json(jsonIStream, 
  58.             wptParse); 
  59.         int num = wptParse.get<int>(L"root.num"); 
  60.         std::wstring wstrVal = wptParse.get<std::wstring>(L"root.str"); 
  61.         std::wcout << L"Num=" << std::dec << num 
  62.             << L" Str=" << wstrVal << std::endl << std::endl; 
  63.     } 
  64.     catch (...) 
  65.     { 
  66.         printf("create boost::property_tree::wptree failed\n"); 
  67.     } 
  68.  
  69.     return 0; 
#include <stdio.h>

#include <iostream>
#include <sstream>
#include <string>
#include <locale>

#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/json_parser.hpp"
#include "boost/property_tree/xml_parser.hpp"

#include "boost/program_options/detail/convert.hpp"
#include "boost/program_options/detail/utf8_codecvt_facet.hpp"

int main(int argc, char **argv)
{
    /* The data format
     * <root>
     *  <num>1</num>
     *  <str>Test</str>
     * </root>
     */
    /* test UTF-8 format */
    try
    {
        /* create boost utf8 codecvt */
        std::locale oldLocale;
        std::locale utf8Locale(oldLocale,
            new boost::program_options::detail::utf8_codecvt_facet());
        std::wcout.imbue(utf8Locale);

        /* create the wptree for save the UTF-8 data */
        boost::property_tree::wptree datum;
        datum.put(L"root.num", 100);
        datum.put(L"root.str", L"wstring");

        /* output XML string */
        std::wostringstream xmlOutputStream;
        xmlOutputStream.imbue(utf8Locale);
        boost::property_tree::xml_parser::write_xml(xmlOutputStream,
            datum);
        std::wcout << L"XML format:" << std::endl;
        std::wcout << xmlOutputStream.str() << std::endl;

        /* output JSON string */
        std::wostringstream jsonOutputStream;
        jsonOutputStream.imbue(utf8Locale);
        boost::property_tree::json_parser::write_json(jsonOutputStream,
            datum);
        std::wcout << L"JSON format:" << std::endl;
        std::wcout << jsonOutputStream.str() << std::endl;

        /* read datum from JSON stream */
        boost::property_tree::wptree wptParse;
        std::wistringstream jsonIStream;
        jsonIStream.imbue(utf8Locale);
        jsonIStream.str(jsonOutputStream.str());
        boost::property_tree::json_parser::read_json(jsonIStream,
            wptParse);
        int num = wptParse.get<int>(L"root.num");
        std::wstring wstrVal = wptParse.get<std::wstring>(L"root.str");
        std::wcout << L"Num=" << std::dec << num
            << L" Str=" << wstrVal << std::endl << std::endl;
    }
    catch (...)
    {
        printf("create boost::property_tree::wptree failed\n");
    }

    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值