是否有任何类似于C#(SelectSingleNode()等)的XPATH使用方式。
我正在尝试使用boost::property_tree::ptree,但它与C#/ VBA XML解析有点不同。
<?xml version="1.0"?>
<Classes>
<Class name="first">
<Elements>
<ElementA>aa</ElementA>
<ElementB>bb</ElementB>
</Elements>
</Class>
<Class name="second">
<Elements>
<ElementA>cc</ElementA>
<ElementB>dd</ElementB>
</Elements>
</Class>
<Class name="third">
<Elements>
<ElementA>ee</ElementA>
<ElementB>ff</ElementB>
</Elements>
</Class>
</Classes>
我必须迭代这种配置,并根据Classes / Class [@name]属性选择子树。
我如何用ptree做到这一点。
最佳答案
没有几个很好的链接来了解ptree的数据结构,并且从那里很容易。
从这里开始,Boost property tree : how to get child of child tree with a xml file
然后在这里https://akrzemi1.wordpress.com/2011/07/13/parsing-xml-with-boost/
#include <iostream>
#include <string>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <fstream>
int main()
{
std::string xml = R"(<?xml version="1.0"?>
<Classes>
<Class name="first">
<Elements>
<ElementA>aa</ElementA>
<ElementB>bb</ElementB>
</Elements>
</Class>
<Class name="second">
<Elements>
<ElementA>cc</ElementA>
<ElementB>dd</ElementB>
</Elements>
</Class>
<Class name="third">
<Elements>
<ElementA>ee</ElementA>
<ElementB>ff</ElementB>
</Elements>
</Class>
</Classes>)";
//std::cout << xml;
using boost::property_tree::ptree;
std::stringstream ss(xml);
ptree p;
read_xml(ss,p);
std::ostringstream subTree;
BOOST_FOREACH( ptree::value_type const& v, p.get_child("Classes") )
{
//if(v.second.get<std::string>("<xmlattr>.name") == "first")
write_xml(subTree, v.second);
std::cout << subTree.str();
std::cout << "\n====================\n";
}
}