C++使用boost讀取xml文件

    boost中提供了對配置文件讀取的支持,它就是:property_tree。

    basic_ptree 是property_tree的核心基礎。其接口像std::list。可以執行很多基本的元素操作,比如使用begin()、end()等。

    此外還加入了操作屬性樹的get()、get_child()、get_value()、data()等額外的操作。

    basic_ptree有兩個重要的內部定義self_type和value_type。self_type是basic_ptree模板實例化後自身的類型,它也是子節點的類型。value_type是節點的數據結構,它是一個std::pair,它含有屬性名(first)和節點自身(second)。

    通常不使用basic_ptree,而是使用預定義的typedef。ptree、wptree、iptree、wiptree。前綴i表示忽略大小寫,前綴w表示支持寬字符。

例如:

config.xml

<?xml version="1.0" encoding="utf-8"?>
<con>
  <id>1</id>
  <name>fansy</name>
  <urls>
    <url>http://blog.csdn.net//fansongy</url>
    <url>http://weibo.com//fansongy</url>
  </urls>
</con> 

讀取它的數據:

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/typeof/typeof.hpp>  
using namespace std;
using namespace boost::property_tree;
int  main()
{
    ptree pt;
    read_xml("conf.xml",pt);     //讀入一個xml文件
    cout<<"ID is "<<pt.get<int>("con.id")<<endl;  //讀取節點中的信息
    cout<<"Try Default"<<pt.get<int>("con.no_prop",100)<<endl;  //如果取不到,則使用默認值
    ptree child = pt.get_child("con");    //取一個子節點
    cout<<"name is :"<<child.get<string>("name")<<endl;    //對子節點操作,其實跟上面的操作一樣
    
    child = pt.get_child("con.urls");
    for(BOOST_AUTO(pos,child.begin());pos != child.end();++pos)  //boost中的auto
     {
         cout<<"\t"+pos->second.data()<<endl;
     }
    pt.put("con.name","Sword");    //更改某個鍵值
    pt.add("con.urls.url",http://www.baidu.com); //增加某個鍵值
    write_xml("conf.xml",pt);    //寫入XML
    getchar();
    return 0;
}

則輸出為:

ID is 1
Try Default100
name is :fansy
        http://blog.csdn.net//fansongy
        http://weibo.com//fansongy

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章