对xml的解析可能大家都很熟悉,网上流传比较多的代码一般都是对xml结构比较简单进行的操作,如果对结构像下面这样该怎么解析呢:
<root>
<strage>
<id>"12"</id>
<name>"jack"</name>
<accout>"0001"</accout>
</strage>
<strage>
<id>"13"</id>
<name>"toni"</name>
<accout>"0002"</accout>
</strage>
<strage>
<id>"14"</id>
<name>"hate"</name>
<accout>"0003"</accout>
</strage>
</root>
看到大家都在纠结这个解析器怎么写。我这里用boost提供的xml_parser来解决这个问题,效果非常好,既然已经提供了一个非常强大的工具为什么不去用呢?好吧如果你对boost不熟悉或者不知道怎么部署,请看我前面的一个博客,先上代码(在vs2008上调试通过,前提是已经配置了boost环境):
#include "stdafx.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <set>
#include <vector>
#include <exception>
#include <iostream>
using namespace std;
static const string str_node_name[] = {"id","name","accout"};
struct xmlStageDetail
{
string id;
string name;
string accout;
};
int load(const char* filename,vector<xmlStageDetail>*m_xml_detail)
{
xmlStageDetail xml_stage_detail;
using boost::property_tree::ptree;
ptree pt;
ptree root;
try
{
read_xml(filename, pt);
root = pt.get_child("root");
}
catch (std::exception& e)
{
return -1;
}
for (ptree::iterator itr = root.begin();itr!=root.end();itr++)
{
ptree strage = itr->second;
for (int i = 0;i<3;i++)
{
ptree pt;
string str_value;
try
{
pt = strage.get_child(str_node_name[i]);
str_value = pt.data();
}
catch (std::exception& e)
{
return -1;
}
switch (i)
{
case 0:
xml_stage_detail.id = str_value;
break;
case 1:
xml_stage_detail.name = str_value;
break;
case 2:
xml_stage_detail.accout = str_value;
break;
}
}
m_xml_detail->push_back(xml_stage_detail);
}
return 0;
}
int main()
{
vector<xmlStageDetail>m_xml_detail;
try
{
load("debug_settings.xml",&m_xml_detail);
std::cout << "Success\n";
}
catch (std::exception &e)
{
std::cout << "Error: " << e.what() << "\n";
return -1;
}
return 0;
}