使用boost讀取XML文件詳細(xì)介紹
boost讀取XML文件
boost中提供了對配置文件讀取的支持,它就是:property_tree。
basic_ptree 是property_tree的核心基礎(chǔ)。其接口像std::list??梢詧?zhí)行很多基本的元素操作,比如使用begin()、end()等。
此外還加入了操作屬性樹的get()、get_child()、get_value()、data()等額外的操作。
basic_ptree有兩個重要的內(nèi)部定義self_type和value_type。self_type是basic_ptree模板實(shí)例化后自身的類型,它也是子節(jié)點(diǎn)的類型。value_type是節(jié)點(diǎn)的數(shù)據(jù)結(jié)構(gòu),它是一個std::pair,它含有屬性名(first)和節(jié)點(diǎn)自身(second)。
通常不使用basic_ptree,而是使用預(yù)定義的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>
我要讀取它的數(shù)據(jù):
#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; //讀取節(jié)點(diǎn)中的信息 cout<<"Try Default"<<pt.get<int>("con.no_prop",100)<<endl; //如果取不到,則使用默認(rèn)值 ptree child = pt.get_child("con"); //取一個子節(jié)點(diǎn) cout<<"name is :"<<child.get<string>("name")<<endl; //對子節(jié)點(diǎn)操作,其實(shí)跟上面的操作一樣 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; }
運(yùn)行的顯示為: 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>
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
基于C語言實(shí)現(xiàn)的aes256加密算法示例
這篇文章主要介紹了基于C語言實(shí)現(xiàn)的aes256加密算法,結(jié)合具體實(shí)例形式詳細(xì)分析了C語言實(shí)現(xiàn)的aes256加密算法實(shí)現(xiàn)步驟與使用技巧,需要的朋友可以參考下2017-02-02c語言實(shí)現(xiàn)輸入一組數(shù)自動從大到小排列的實(shí)例代碼
下面小編就為大家?guī)硪黄猚語言實(shí)現(xiàn)輸入一組數(shù)自動從大到小排列的實(shí)例代碼。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-09-09詳解C語言中scanf函數(shù)使用的一些注意點(diǎn)
這篇文章主要介紹了C語言中scanf函數(shù)使用的一些注意點(diǎn),scanf函數(shù)的使用是C語言入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2016-04-04wxWidgets實(shí)現(xiàn)無標(biāo)題欄窗口拖動效果
這篇文章主要為大家詳細(xì)介紹了wxWidgets實(shí)現(xiàn)無標(biāo)題欄窗口拖動效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-02-02