Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ simple parse with boost xml with property tree

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

like image 399
ghiboz Avatar asked Dec 08 '25 19:12

ghiboz


1 Answers

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";
    }
};
like image 83
sehe Avatar answered Dec 10 '25 08:12

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!