帮助使用 Boost 库解析 xml。
我想使用 boost 获取父节点内的所有子节点。以下是我的 xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<info>
<books>
<book>"Hello"</book>
<book>"World"</book>
</books>
</info>
我需要获取书籍的名称(“Hello”
、“World”
)。
如何使用 boost 库来完成此任务?
最佳答案
您可以使用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;
}
关于c++ - 如何获取所有子节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35954432/