c++ - 如何获取所有子节点值

标签 c++ xml boost xml-parsing

帮助使用 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/

相关文章:

c++ - 通过从Opencv中的一个正方形检测到的4个点计算俯仰,横滚和偏航

c++ - 如何在 C++ 中分配矩阵?

java - XML 绑定(bind)生成文件不编译

java - 在 Sax 解析器 (XML) 中处理外部实体和样式表

c# - 通过在 xslt 中调用 C# 函数来更改 xml 文件

c++ - 如何通过句柄从 boost::fibonacci_heap 获取元素?

c++ - 异常 C++,我只是不明白为什么输出是这样的

c++ - SFML 2.0 – 用 Sprite vector 绘图

c++ - 使用 Accept() 的 Boost 线程中的性能/优先级 (Linux)

c++ - 如何在 Linux 中安装仅 header (odeint) 库?