boost::property_tree

來源:互聯網
上載者:User


boost::property_tree 的解析xml模組是基於rapidXml的, 以下是兩個例子:

例子1: 

#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*/

<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: 

#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 debugBOOST_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 typecout<< "  module type:" << v1.second.get<string>("<xmlattr>.type") << endl;//loop for every node under modulesBOOST_FOREACH(ptree::value_type &v2, v1.second){if(v2.first == "<xmlattr>"){  //it's an attribute//this can also get module typecout<< "  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}



<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 )。

至少可以用在: 進程間通訊或者跨語言的進程間的通訊 一些設定檔的存取 網路通訊協議的格式 基本用法

基本用法有 2 種情境。第一種是從 Property Tree儲存到具體格式。第二種是從具體格式解析到具體的 Property Tree。其他還有一些 Property Tree 操作的方法,比如:遍曆、搜尋等方法。

以下這個 Sample 就是基本用法的測試:

先把 資料存放區到 datum 中,隨後輸出 相應的 XML 和 JSON 到 std::cout 上。最後再從 JSON Stream 中解析輸入到 ptParse 中獲得相應 的資料。

#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 裡做轉換。

#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;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.