2013-03-22 46 views
2

我有這樣升壓ptree中迭代在兩個節點

<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> 

我嘗試這個代碼的XML它僅提取第一示例節點

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

我相信[this](http://liveworkspace.org/code/I3seD$0)是你想要的。 – 2013-03-22 07:05:42

回答

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; 
}