使用boost讀取XML檔案詳細介紹_C 語言

來源:互聯網
上載者:User

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 
config.xml為: <?xml version="1.0" encoding="utf-8"?> <con>  <id>1</id>  <name>Sword</name> <urls>    <url>http://blog.csdn.net//fansongy</url>    <url>http://weibo.com//fansongy</url>    <url>http://www.baidu.com</url> </urls> </con>  

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.