使用Boost property tree来解析带attribute的xml


boost property tree的5分钟教程虽然简单明了,可惜使用的xml不够典型。今天由于工作上要读取带属性并且有几层嵌套的xml配置文件,因此研究了一下如何使用。下面直接列出测试用的xml文件内容和程序代码。


debug_settings.xml,在boost的例子上改得稍微复杂一些。


    
    
        Finance_Internal
        Admin_Internal
        HR_Internal
    
    
    
        Finance_External
        Admin_External
        HR_External  
    


Source code:

#include 
#include 
#include 
#include 
#include 

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 == ""){ //it's an attribute
			//read debug name="debugname"
			cout<< "debug name=" << v1.second.get("name") << endl;
		}else if(v1.first == "file"){
			//read file name="debug.log"
			cout << "  file name=" << v1.second.get(".name") << endl;
		}
		else{ // v1.first == "modules"
			//get module type
			cout<< "  module type:" << v1.second.get(".type") << endl;

			//loop for every node under modules
			BOOST_FOREACH(ptree::value_type &v2, v1.second){
				if(v2.first == ""){  //it's an attribute
					//this can also get module type
					cout<< "  module type again:" << v2.second.get("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

你可能感兴趣的:(C/C++,tree,module,file,xml,structure,测试)