hansgans
hansgans

Reputation: 337

boost::property_tree passing subtree including <xmlattr>

I'm trying to pass elements of a boost::property_tree::ptree to a function. In detail, I have to following XML code from which a ptree is initialised:

<Master Name='gamma'>
    <Par1 Name='name1'>
        <Value>0.</Value>
        <Fix>1</Fix>
    </Par1>
    <Par2 Name='name2'>
        <Value>0.</Value>
        <Fix>1</Fix>
    </Par2>
</Master>

I would like to pass part of it to a function. Basically I want to pass:

   <Par2 Name='name2'>
        <Value>0.</Value>
        <Fix>1</Fix>
    </Par2>

The function could look like this:

 void processTree( which_type_do_I_put_here element ){
     std::string n = element.get<std::string>("<xmlattr>.Name");
     double val = element.get<double>("Value");
 }

In general I could pass a subtree using ptree::get_child("par2"). This has the disadvantage that the function has no access to <xmlattr> of this node.

How can I pass this part of the tree with access to <xmlattr>? Thanks in advance for any ideas.

~Peter

Upvotes: 2

Views: 1044

Answers (1)

sehe
sehe

Reputation: 392979

The type is a ptree.

In general I could pass a subtree using ptree::get_child("par2").

Indeed.

This has the disadvantage that the function has no access to of this node

That's not right:

Live On Coliru

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

std::string const sample = R"(
<Master Name='gamma'>
    <Par1 Name='name1'>
        <Value>0.</Value>
        <Fix>1</Fix>
    </Par1>
    <Par2 Name='name2'>
        <Value>0.</Value>
        <Fix>1</Fix>
    </Par2>
</Master>
)";

using boost::property_tree::ptree;

void processTree(ptree const& element) {
     std::string n = element.get<std::string>("<xmlattr>.Name");

     double val = element.get<double>("Value");
     std::cout << __FUNCTION__ << ": n=" << n << " val=" << val << "\n";
}

int main() {
    ptree pt;
    {
        std::istringstream iss(sample);
        read_xml(iss, pt);
    }

    processTree(pt.get_child("Master.Par2"));
}

Which prints:

processTree: n=name2 val=0

Upvotes: 3

Related Questions