我有像这样的xml
<examples>
<example>
<test name="img">testme</test>
<test name="img1">testme1</test>
<test name="img1">testme2</test>
</example>
<example>
<test name="text">testme</test>
<test name="text">testme1</test>
<test name="text">testme2</test>
</example>
</examples>
我尝试了这段代码,它只提取了第一个示例节点
ptree ptree;
read_xml(doc_path, ptree);
BOOST_FOREACH(ptree::value_type & value, ptree.get_child("examples.example")){
cout<<value.second.get("<xmlattr>.name", "")<<endl;
cout<<value.second.data()<<endl;
}
答案 0 :(得分:6)
ptree.equal_range方法具有您正在寻找的行为。注意,我在那里有几个C ++ 11 - 你需要一个现代的编译器。
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <sstream>
const char xml[] = R"(<examples>
<example>
<test name="img">testme</test>
<test name="img1">testme1</test>
<test name="img1">testme2</test>
</example>
<example>
<test name="text">testme</test>
<test name="text">testme1</test>
<test name="text">testme2</test>
</example>
</examples>)";
int main(int argc, char **argv)
{
boost::property_tree::ptree ptree;
std::istringstream xml_str(xml);
read_xml(xml_str, ptree);
auto example_range = ptree.get_child("examples").equal_range("example");
for( auto it = example_range.first; it != example_range.second; ++it )
{
auto test_range = it->second.equal_range("test");
for( auto test_it = test_range.first; test_it != test_range.second; ++test_it )
{
std::cout << test_it->second.get("<xmlattr>.name","") <<std::endl;
std::cout << test_it->second.data() << std::endl;
}
}
return 0;
}