3

I have this question about the boost xml parsing:

here is a piece of my Xml:

<Clients>
  <Client name="Alfred" />
  <Client name="Thomas" />
  <Client name="Mark" />
</Clients>

and I read the name with this code:

std::string name = pt.get<std::string>("Clients.Client.<xmlattr>.name, "No name");

and works fine, but retrieve always the first node..

Is there a way to get the second, third node without looping?

thanks

1 Answer 1

5

There's no facility to query multi-valued keys in Property Tree. (Partly because most of the supported backend formats do not officially support duplicate keys).

However, you can iterate through child elements, so you can implement your own query, like so:

for (auto& child : pt.get_child("Clients"))
    if (child.first == "Client")
        std::cout << child.second.get<std::string>("<xmlattr>.name", "No name") << "\n";

See fully working sample Live On Coliru:

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

using boost::property_tree::ptree;

int main()
{
    std::stringstream ss("<Clients>\n"
        "  <Client name=\"Alfred\" />\n"
        "  <Client name=\"Thomas\" />\n"
        "  <Client name=\"Mark\" />\n"
        "</Clients>");

    ptree pt;
    boost::property_tree::read_xml(ss, pt);

    for (auto& child : pt.get_child("Clients"))
    {
        if (child.first == "Client")
            std::cout << child.second.get<std::string>("<xmlattr>.name", "No name") << "\n";
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

May I trouble you to correct your hyperlink? Im unable to access and would like to see the content. Thanks in advance!
@IdusOrtus The link works for me. Can you try again?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.