【问题标题】:How to get all child node values如何获取所有子节点值
【发布时间】:2016-03-12 06:13:12
【问题描述】:
帮助使用 Boost 库解析 xml。
我想使用 boost 获取父节点中的所有子节点。以下是我的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<info>
<books>
<book>"Hello"</book>
<book>"World"</book>
</books>
</info>
我需要获取书名("Hello"、"World")。
如何使用 boost 库来完成这项工作?
【问题讨论】:
标签:
c++
xml
boost
xml-parsing
【解决方案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;
}