参考:https://www.2cto.com/kf/201210/162103.html
conf.xml 注:文件放在当前项目根就行了
<?xml version="1.0" encoding="utf-8"?>
<root>
<strage name="asd" alias="13" classId="13.22">r
<id>12</id>
<name>"jack"</name>
<accout>"0001"</accout>
</strage>
<strage name="abbasd" alias="14" classId="14.22">abb
<id >13</id>
<name>"toni"</name>
<accout>"0002"</accout>
</strage>
<strage name="assasd" alias="15" classId="15.44">ass
<id >14</id>
<name>"hate"</name>
<accout>"0003"</accout>
</strage>
</root>
main.cpp
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <set>
#include <vector>
#include <exception>
#include <iostream>
using namespace std;
const std::string str_node_name[] = { "id", "name", "accout" };
struct xmlStageDetail
{
std::string id;
std::string name;
std::string accout;
};
int load(const char* filename, std::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)
{
std::cout << "Error: " << e.what() << endl;
return -1;
}
std::cout << "root的长度:" << root.size() << endl;
/*******************************************************/
int ita = pt.get<int>("root.strage.id");
std::string cattr = pt.get<string>("root.strage.<xmlattr>.name");
/***************************************************************/
std::cout << "root.strage.id:" << ita << "\nroot.strage.<xmlattr>.name:" << cattr << endl;
for (ptree::iterator itr = root.begin(); itr != root.end(); itr++)
{
ptree strage = itr->second;
std::string ssv = strage.data();
std::string sattr = strage.get<string>("<xmlattr>.name");
int iattr = strage.get<int>("<xmlattr>.alias");
float fattr = strage.get<float>("<xmlattr>.classId");
// 去除首尾空格
boost::trim<std::string>(ssv);
std::cout << endl;
std::cout << ssv <<endl<< "name:" << sattr << "\talias:" << iattr << "\tclassid:" << fattr << endl;
for (int i = 0; i < root.size(); i++)
{
ptree pt;
std::string str_value;
try
{
pt = strage.get_child(str_node_name[i]);
str_value = pt.data();
std::cout << str_value << "\t";
}
catch (std::exception& e)
{
cout << str_value << "解析错误:" << e.what() << endl;
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);
std::cout << endl;
}
return 0;
}
int main()
{
vector<xmlStageDetail>m_xml_detail;
try
{
load("conf.xml", &m_xml_detail);
std::cout << "Success\n";
std::cout << endl;
}
catch (std::exception &e)
{
std::cout << "Error: " << e.what() << endl;
std::cout << endl;
return -1;
}
system("pause");
return 0;
}
效果图