转自:https://blog.csdn.net/mosaic/article/details/6888934
boost property tree的5分钟教程虽然简单明了,可惜使用的xml不够典型。今天由于工作上要读取带属性并且有几层嵌套的xml配置文件,因此研究了一下如何使用。下面直接列出测试用的xml文件内容和程序代码。
debug_settings.xml,在boost的例子上改得稍微复杂一些。
- <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>
Source code:
- #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_settings.xml", pt);
- //loop for every node under debug
- BOOST_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 type
- cout<< " module type:" << v1.second.get<string>("<xmlattr>.type") << endl;
- //loop for every node under modules
- BOOST_FOREACH(ptree::value_type &v2, v1.second){
- if(v2.first == "<xmlattr>"){ //it's an attribute
- //this can also get module type
- cout<< " 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
- }
程序输出如下:
debug name=debugname
file name=debug.log
module type:internal
module type again:internal
module name:Finance_Internal
module name:Admin_Internal
module name:HR_Internal
module type:external
module type again:external
module name:Finance_External
module name:Admin_External
module name:HR_External