boost解析xml文件

前面我們介紹了xml文件,今天我們試著用boost庫來解析xml文件。我們將舉兩個例子來說明怎么使用。

來自boost官方的例子

先看xml文件的內容:

<debug><filename>debug.log</filename><modules><module>Finance</module><module>Admin</module><module>HR</module></modules><level>2</level>
</debug>

我們再來看如何使用boost讀取和保存xml文件。

// ----------------------------------------------------------------------------
// Copyright (C) 2002-2006 Marcin Kalicinski
//
// Distributed under the Boost Software License, Version 1.0. 
// (See accompanying file LICENSE_1_0.txt or copy at 
// http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see www.boost.org
// ----------------------------------------------------------------------------#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>struct debug_settings
{std::string m_file;               // log filenameint m_level;                      // debug levelstd::set<std::string> m_modules;  // modules where logging is enabledvoid load(const std::string &filename);void save(const std::string &filename);
};void debug_settings::load(const std::string &filename)
{// Create empty property tree objectusing boost::property_tree::ptree;ptree pt;// Load XML file and put its contents in property tree. // No namespace qualification is needed, because of Koenig // lookup on the second argument. If reading fails, exception// is thrown.read_xml(filename, pt);// Get filename and store it in m_file variable. Note that // we specify a path to the value using notation where keys // are separated with dots (different separator may be used // if keys themselves contain dots). If debug.filename key is // not found, exception is thrown.m_file = pt.get<std::string>("debug.filename");// Get debug level and store it in m_level variable. This is // another version of get method: if debug.level key is not // found, it will return default value (specified by second // parameter) instead of throwing. Type of the value extracted // is determined by type of second parameter, so we can simply // write get(...) instead of get<int>(...).m_level = pt.get("debug.level", 0);// Iterate over debug.modules section and store all found // modules in m_modules set. get_child() function returns a // reference to child at specified path; if there is no such // child, it throws. Property tree iterator can be used in // the same way as standard container iterator. Category // is bidirectional_iterator.//BOOST_FOREACH(ptree::value_type &v, pt.get_child("debug.modules"))//    m_modules.insert(v.second.data());}void debug_settings::save(const std::string &filename)
{// Create empty property tree objectusing boost::property_tree::ptree;ptree pt;// Put log filename in property treept.put("debug.filename", m_file);// Put debug level in property treept.put("debug.level", m_level);// Iterate over modules in set and put them in property// tree. Note that the add function places new key at the// end of list of keys. This is fine in most of the// situations. If you want to place item at some other// place (i.e. at front or somewhere in the middle),// this can be achieved using a combination of the insert// and put_value functionsBOOST_FOREACH(const std::string &name, m_modules)pt.add("debug.modules.module", name);// Write property tree to XML filewrite_xml(filename, pt); //write_xml(cout,pt); //這個函數有重載. 可以用流 也可直接用文件名. }int main()
{try{debug_settings ds;ds.load("debug_settings.xml");ds.save("debug_settings_out.xml");std::cout << "Success\n";}catch (std::exception &e){std::cout << "Error: " << e.what() << "\n";}return 0;
}

解析:

load函數:

首先定義了解析樹

using boost::property_tree::ptree;ptree pt;

然后讀取xml文件
接下來三行代碼,讀取文件里的內容。
我們注意到:
上面的xml的根節點是debug。然后有三個節點:filename,modules,level。
其中modules是一個含有子節點的復合節點。
于是:
1.

    m_file = pt.get<std::string>("debug.filename");

讀取filename。如讀取失敗,則拋出異常。
2.

m_level = pt.get("debug.level", 0);

獲取level數,當然了我們也可以通過和前一句一樣的語法獲取m_level:

m_level = pt.get<int>("debug.level");

但是同樣這句話一旦獲取不到,就會拋出異常,如果我們想獲取不到,返回一個默認值0呢?此時可以使用

m_level = pt.get("debug.level", 0);

來實現。其中最后返回值的類型通過默認值來推斷,非常類似c++11的auto語法。
3.

BOOST_FOREACH(ptree::value_type &v, pt.get_child("debug.modules"))m_modules.insert(v.second.data());

由于modules是一個復合節點,我們可以通過循環遍歷的方法訪問節點的子節點。
BOOST_FOREACH類似c++11的for(auto& value: range)
循環遍歷的第一句就是:<module>Finance</module>,而v.first==module,v.second==Finance,但是我們要通過data()來獲取。
我們可以通過改變上述語句為下面語句驗證我的推斷:

BOOST_FOREACH(ptree::value_type &v, pt.get_child("debug.modules")){std::cout << v.first<< " "<<v.second.data()<<std::endl;m_modules.insert(v.second.data());}

值得注意的是我測試的時候發現獲取first加不加.data()都可以,但獲取second必須加.data().

save函數

實際上是read的翻譯版,只需將get換成put即可.我們只要按照變量對應的標簽加即可。

另一個更復雜的例子

xml文件如下:

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

分析以上xml文件,我們會發現此刻帶有了屬性,還有深層嵌套。分析起來,稍復雜一些。前面我們講過xml文件中屬性其實可以看成子元素的形式。因此我們對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>

然后我們看代碼:

#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_settings2.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
}

注意:
對于屬性來說,first指”<xmlattr>“,而不是“name”,v.second指的是name的具體值.

參考文獻:

1.使用Boost property tree來解析帶attribute的xml
2.http://www.boost.org/doc/libs/1_46_1/doc/html/boost_propertytree/tutorial.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/258961.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/258961.shtml
英文地址,請注明出處:http://en.pswp.cn/news/258961.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

使用網橋模式(bridge networking mode)配置KVM-QUME虛擬機網絡

&#xff08;1&#xff09;linux要工作在網橋模式&#xff0c;所以必須安裝兩個RPM包。即&#xff1a;bridge-utils和tunctl。它們提供所需的brctl、tunctl命令行工具。能夠使用yum在線安裝&#xff1a; [rootserver3 ~]# yum install bridge-utils &#xff08;2&#xff09;查…

python數據處理常用函數_pandas數據分析常用函數總結大全:上篇

基礎知識在數據分析中就像是九陽神功&#xff0c;熟練的掌握&#xff0c;加以運用&#xff0c;就可以練就深厚的內力&#xff0c;成為絕頂高手自然不在話下&#xff01; 為了更好地學習數據分析&#xff0c;我對于數據分析中pandas這一模塊里面常用的函數進行了總結。整篇總結&…

XML的應用

1.XML的定義: XML 于 1998 年 2 月 10 日成為 W3C 的推薦標準。xml一般指可擴展標記語言&#xff0c;可擴展標記語言是一種很像超文本標記語言的標記語言。它的設計宗旨是傳輸數據&#xff0c;而不是顯示數據。 2.通過XML我們可以自定義自己的標簽&#xff0c;如&#xff1a; &…

虛擬機VMware里 windows server 2003 擴充C盤方法

你會經常用windows server 2003 嗎&#xff1f;應該不會吧&#xff0c;有時一些東西必須裝在windows server 2003 上才能用&#xff0c;所以 用虛擬機把&#xff0c;好&#xff0c;裝在虛擬機上&#xff0c;8G的C盤夠你用嗎&#xff0c;一個稍微大點的軟件就可能就沒空間來存儲…

從運維角度淺談MySQL數據庫優化

一個成熟的數據庫架構并不是一開始設計就具備高可用、高伸縮等特性的&#xff0c;它是隨著用戶量的增加&#xff0c;基礎架構才逐漸完善。這篇博文主要談MySQL數據庫發展周期中所面臨的問題及優化方案&#xff0c;暫且拋開前端應用不說&#xff0c;大致分為以下五個階段&#x…

c語言c99標準_自學C語言之一

上次自學C語言還是在剛開學到國慶期間&#xff0c;聽學姐的建議買了本C語言的書&#xff0c;在軍訓期間的晚上翻翻看看。后來選課、開始正式上課、面試社團、開各種會等等&#xff0c;好像每天都有許多事要忙&#xff0c;但又沒忙出來什么結果&#xff0c;慢慢地好像就把C語言放…

boost解析info文件

先給出info文件&#xff1a; parameters {MAX_STAGES 4MAX_DEPTH 3MAX_NUMTRESS 5MAX_NUMTHRESHS 500MAX_NUMFEATS 1000,1000,1000,500,500,500,400,400MAX_RATIO_RADIUS 0.3,0.2,0.2,0.15,0.12,0.10,0.08,0.06,0.06,0.05BAGGING_OVERLAP 0.4IS_FLIP true }meanface {MAX_ITER…

Font Rending 的 Hint 機制對排版的影響

Font Rending 的 Hint 機制對排版的影響【轉】 在設計一種 Font 時&#xff0c;設計者使用的是一個抽象的單位&#xff0c;叫做 EM&#xff0c;來源于大寫 M 的寬度&#xff08;通常英文字體中大寫 M 的寬度最大&#xff09;。EM 即不同于在屏幕顯示時用的像素&#xff08;Pixe…

《SQL初學者指南(第2版)》——2.4 指定列

本節書摘來自異步社區出版社《SQL初學者指南&#xff08;第2版&#xff09;》一書中的第2章&#xff0c;第2.4節&#xff0c;作者&#xff1a;【美】Larry Rockoff&#xff0c;更多章節內容可以訪問云棲社區“異步社區”公眾號查看。 2.4 指定列 到目前為止&#xff0c;我們只…

python從文件中提取特定文本_使用Python從HTML文件中提取文本

我發現最好的一段代碼用于提取文本&#xff0c;而不需要javascript或不需要的東西&#xff1a;import urllibfrom bs4 import BeautifulSoupurl "http://news.bbc.co.uk/2/hi/health/2284783.stm"html urllib.urlopen(url).read()soup BeautifulSoup(html)# kill …

mutable、volatile的使用

本文轉載自http://blog.csdn.net/tht2009/article/details/6920511 (1)mutable 在C中&#xff0c;mutable是為了突破const的限制而設置的。被mutable修飾的變量&#xff0c;將永遠處于可變的狀態&#xff0c;即使在一個const函數中&#xff0c;甚至結構體變量或者類對象為const…

文本框點擊后文字消失總結

1.文本框顯示默認文字&#xff1a; <textarea>白鴿男孩</textarea> <textarea>白鴿男孩</textarea>    2.鼠標點擊文本框&#xff0c;默認文字消失&#xff1a; <textarea οnfοcus”if(value’白鴿男孩’) {value’ ‘}”>白鴿男孩</text…

[裴禮文數學分析中的典型問題與方法習題參考解答]4.5.8

需要全部的解答, 請 http://www.cnblogs.com/zhangzujin/p/3527416.html 設 $f(x)$ 在 $[a,\infty)$ 上可微; 且 $x\to\infty$ 時, $f(x)$ 單調遞增趨于 $\infty$, 則 $$\bex \int_a^\infty \sin f(x)\rd x,\quad \int_a^\infty \cos f(x)\rd x \eex$$ 都收斂. 證明: 由 $$\be…

《PowerShell V3——SQL Server 2012數據庫自動化運維權威指南》——2.13 創建視圖...

本節書摘來自異步社區出版社《PowerShell V3—SQL Server 2012數據庫自動化運維權威指南》一書中的第2章&#xff0c;第2.13節&#xff0c;作者&#xff1a;【加拿大】Donabel Santos&#xff0c;更多章節內容可以訪問云棲社區“異步社區”公眾號查看。 2.13 創建視圖 本方案展…

python刷抖音_用Python生成抖音字符視頻!

抖音字符視頻在去年火過一段時間。 反正我是始終忘不了那段極樂凈土的音樂... 這一次自己也來實現一波&#xff0c;做一個字符視頻出來。 主要用到的庫有cv2&#xff0c;pillow庫。 原視頻如下&#xff0c;直接抖音下載的&#xff0c;妥妥的水印。 不過并不影響本次的操作。 / …

變長參數

轉載自&#xff1a;http://blog.csdn.net/tht2009/article/details/7019635 變長參數 設計一個參數個數可變、參數類型不定的函數是可能的&#xff0c;最常見的例子是printf函數、scanf函數和高級語言的Format函數。在C/C中&#xff0c;為了通知編譯器函數的參數個數和類型可變…

第十七章 我國農業科學技術

農村改革解說&#xff08;專著&#xff09;第十七章 第十七章 我國農業科學技術 1、為什么說科學技術是生產力&#xff1f; 我們說科學技術是生產力&#xff0c;是因為在構成生產力的兩個主要因素中&#xff0c;都包含著科學技術在內。 A、生產力中人的因素是同一定的科學技術緊…

《淘寶網開店 拍攝 修圖 設計 裝修 實戰150招》一一1.2 選購鏡頭時應注意的事項...

本節書摘來自異步社區出版社《淘寶網開店 拍攝 修圖 設計 裝修 實戰150招》一書中的第1章&#xff0c;第1.2節&#xff0c;作者&#xff1a; 葛存山&#xff0c;更多章節內容可以訪問云棲社區“異步社區”公眾號查看。 1.2 選購鏡頭時應注意的事項 面對如此之多的鏡頭&#xf…

OpenCV中的神器Image Watch

Image Watch是在VS2012上使用的一款OpenCV工具&#xff0c;能夠實時顯示圖像和矩陣Mat的內容&#xff0c;跟Matlab很像&#xff0c;方便程序調試&#xff0c;相當好用。跟VS2012配合使用&#xff0c;簡直就是一款神器&#xff01;讓我一下就愛上它了&#xff01; 下面介紹一些鏈…

python異步_Python通過Thread實現異步

當long函數耗時較長時&#xff0c;需要程序先向下執行&#xff0c;這就需要異步&#xff0c;改寫代碼如下&#xff1a; import _thread import time def long(cb): print (long execute) def fun(callback): time.sleep(5) result long end callback(result) _thread.start_ne…