user2677279
user2677279

Reputation: 127

How to get all child node values

Help to parse xml with Boost library.

I wanted to get all child nodes within a parent node using boost. The following is my xml file:

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

I need to get the names of books ("Hello", "World").

How to use boost library to get this done?

Upvotes: 2

Views: 3532

Answers (1)

manlio
manlio

Reputation: 18962

You can use 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;
}

Upvotes: 3

Related Questions