1.准備工作:
環境: visual studio 2010 /boost:boost_1_54_0
新建Application什么的不做贅述,但是注意 如果需要引用Boost庫中的lib 需要在屬性properties的VC++ Directories中的Include Directories 中加入Boost的路徑
待解析xml文件:
text.xml
<students> <student id="1"> <name>張三</name> <age>18</age> <sex>男</sex> </student> <student id="2"> <name>李娟</name> <age>22</age> <sex>女</sex> </student> <student id="3"> <name>王強</name> <age>21</age> <sex>男</sex> </student> <student id="4"> <name>李四</name> <age>25</age> <sex>男</sex> </student> <student id="5"> <name>姚娜</name> <age>19</age> <sex>女</sex> </student> <student id="6"> <name>程樂</name> <age>21</age> <sex>男</sex> </student> </students>
整個程序:
#include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/typeof/typeof.hpp> #include <iostream> #include <exception>
int main()
{
using boost::property_tree::ptree;
ptree pt;
try {
read_xml("text.xml",pt);
BOOST_AUTO(child,pt.get_child("students"));
for(BOOST_AUTO(pos,child.begin());pos!=child.end();++pos)
std::cout<<pos->second.get<int>("<xmlattr>.id")<<" "<<pos->second.get<std::string>("name")<<" "<<pos->second.get<std::string>("sex")<<std::endl;
// system("pause");測試時用,可以讓程序暫時停在此處
}
catch (std::exception& e)
{
std::cout<<"Error:"<<e.what()<<std::endl;
return -1;
}
}
結果:
2.解析流程
a.讀入xml文件
readxml("text.xml");
//注意:這是默認text.xml文件保存在項目文件的根目錄下下,即在硬盤中與主程序文件在同一目錄下,當然也可以放在其他目錄,但別忘了是雙斜杠 位於頭文件#include <boost/property_tree/xml_parser.hpp>
b.獲取子節點
BOOST_AUTO(child,pt.get_child("students"));
//注意:這里的BOOST_AUTO實質上是一個宏,在頭文件#include <boost/typeof/typeof.hpp>中定義,功能說白了就是賦值操作,可以說就是C++ 11中Auto的boost版本,這里定義了一個變量child,並將pt.get_child("students")的值賦給child,
這里為什么要用BOOST_AUTO,實質上是對數據類型的一個泛化,使得用戶不用去深究pt.get_child("students")到底是什么類型,而把重點放在其操作上。詳見C++ 11中auto(配合template將是大殺器)
位於頭文件#include <boost/typeof/typeof.hpp>
c.讀取屬性或節點內容
for(BOOST_AUTO(pos,child.begin());pos!=child.end();++pos) //現在看出了BOOST_AUTO的好處了吧。
{ std::cout<<pos->second.get<int>("<xmlattr>.id")<<" "<<pos->second.get<std::string>("name")<<" "<<pos->second.get<std::string>("sex")<<std::endl; }
此處的pos為節點的迭代器,在本文中即遍歷student節點,此處你可以將pos(迭代器)->second.get<T(類型)>(path)認為是解析的固定方法。注意此處的path.獲取節點內容時直接以點分隔,例如:path="students.student.....";若是求屬性,則加上<xmlattr>