参考来源
http://stackoverflow.com/questions/14010473/parsing-xml-attributes-with-boost
花了两小时,总算解析出来,为了避免遗忘做个笔记
XML 文件 TaskCfg.xml 内容如下
<Tasks>
<EverydayTasks max_count_oneday="5">
<Task id="1000" title="testtestetse" target_count="5" awards="10000|1,10000|2, 20000|3">
<TargetCondition type="get_goods" item_id="3001" />
</Task>
<Task id="1001" title="累计获得[target_count]个[item_id]" target_count="5" awards="10000|1,10000|2, 20000|3">
<TargetCondition type="get_goods" item_id="3001" />
</Task>
<Task id="1002" title="累计获得[target_count]个[item_id]" target_count="5" awards="20000|1">
<TargetCondition type="get_goods" item_id="3002" />
</Task>
<Task id="1003" title="累计获得[target_count]个[item_id]" target_count="5" awards="10000|1">
<TargetCondition type="get_goods" item_id="3003" />
</Task>
<Task id="1004" title="累计获得[target_count]个[item_id]" target_count="5" awards="10000|1">
<TargetCondition type="get_goods" item_id="3004" />
</Task>
<Task id="1005" title="累计获得[target_count]个[item_id]" target_count="5" awards="10000|1">
<TargetCondition type="get_goods" item_id="3005" />
</Task>
</Tasks>
需要解析出各个子节点 Task 中的 id 和 awards 的值
源码如下
#include <iostream>
#include <boost/property_tree/xml_parser.hpp>
using namespace std;
using namespace boost;
using namespace boost::property_tree;
int main( int argc, char* argv[] )
{
ptree pt_empty;
ptree pt;
xml_parser::read_xml( "TaskCfg.xml", pt );
try
{
boost::property_tree::ptree root = pt.get_child( "Tasks" );
ptree pNode_EverydayTasks = pt.get_child( "Tasks.EverydayTasks" );
// 遍历 Task 节点
for( ptree::iterator itr = pNode_EverydayTasks.begin(); itr != pNode_EverydayTasks.end(); itr++ )
{
const ptree & attributes = itr->second.get_child( "<xmlattr>", pt_empty );
for ( ptree::const_iterator itr_attri = attributes.begin(); itr_attri!=attributes.end(); itr_attri++ )
{
if ( "id" == std::string( itr_attri->first.data() ) )
{
cout << " id: " << itr_attri->second.data() << '\t';
}
if ( "awards" == std::string( itr_attri->first.data() ) )
{
cout << "awards: " << itr_attri->second.data() << endl;
}
}
std::cout << std::endl;
}
}
catch( std::exception& e )
{
std::cout << e.what() << std::endl;
}
return 0;
}
注意上面的红色代码行, 必须把 ptree pt_empty; 作为第二个参数, 否则就不能正确解析;比如写成下面这样就解析不出来了
const ptree & attributes = itr->second.get_child( "<xmlattr>" );
boost 源码读起来太恶心了, 路过的朋友要是谁知道原理麻烦告诉我一下