2016-03-12 178 views
1

帮助使用Boost库解析xml。如何获取所有子节点值

我想使用boost来获取父节点中的所有子节点。以下是我的xml文件:

<?xml version="1.0" encoding="utf-8"?> 
<info> 
    <books> 
    <book>"Hello"</book> 
    <book>"World"</book> 
    </books> 
</info> 

我需要的书("Hello""World")的名称。

如何使用boost库来完成这项工作?

回答

1

您可以使用Boost Property Tree

#include <string> 
#include <iostream> 

#include <boost/property_tree/ptree.hpp> 
#include <boost/property_tree/xml_parser.hpp> 

namespace pt = boost::property_tree; 

int main() 
{ 
    std::string filename("test.xml"); 

    // Create empty property tree object 
    pt::ptree tree; 

    // Parse the XML into the property tree. 
    pt::read_xml(filename, tree); 

    // Use `get_child` to find the node containing the books and 
    // iterate over its children. 
    // `BOOST_FOREACH()` would also work. 
    for (const auto &book : tree.get_child("info.books")) 
    std::cout << book.second.data() << '\n'; 

    return 0; 
}