Anonymous
Anonymous

Reputation: 4777

Adding subtree to boost::property_tree element

What I want is this:

<tree>
    <objects>
        <object id="12345678">
            <AdditionalInfo>
                <Owner>Mr. Heik</Owner>
                <Health>37/100</Health>
            </AdditionalInfo>
        </object>
    </objects>
</tree>

What I get is this:

<tree>
    <objects>
        <object id="12345678"/>
        <AdditionalInfo>
            <Owner>Mr. Heik</Owner>
            <Health>37/100</Health>
        </AdditionalInfo>
    </objects>
</tree>

What I tried is this:

using boost::property_tree::ptree;
ptree pt;
boost::property_tree::ptree nodeObject;
nodeObject.put("object.<xmlattr>.id", 12345678);

boost::property_tree::ptree nodeInfo;    
nodeInfo.put("Owner", "Mr. Heik");
nodeInfo.put("Health", "37/100");

// Put everything together
nodeObject.put_child("AdditionalInfo", nodeInfo);
pt.add_child("tree.objects", nodeObject);
write_xml("output.xml", pt);

I tried to get the desired result by using put/add/add_child/etc. but without success. Which boost-functions do I have to use?

Upvotes: 3

Views: 2022

Answers (1)

quantdev
quantdev

Reputation: 23813

This line :

nodeObject.put("object.<xmlattr>.id", 12345678);

Is adding a new child to the subpath "object" of the current node with the given attribute.

Just set your attribute on the Node:

nodeObject.put("<xmlattr>.id", 12345678);

And add the node directly to the correct path in your tree:

pt.add_child("tree.objects.object", nodeObject);

Final code :

ptree pt;
boost::property_tree::ptree nodeObject;
nodeObject.put("<xmlattr>.id", 12345678);

boost::property_tree::ptree nodeInfo;
nodeInfo.put("Owner", "Mr. Heik");
nodeInfo.put("Health", "37/100");

nodeObject.put_child("AdditionalInfo", nodeInfo);
pt.add_child("tree.objects.object", nodeObject);
write_xml("output.xml", pt);

Output :

<?xml version="1.0" encoding="utf-8"?>
<tree>
  <objects>
    <object id="12345678">
       <AdditionalInfo>
          <Owner>Mr. Heik</Owner>
          <Health>37/100</Health>
       </AdditionalInfo>
    </object>
  </objects>
</tree>

Upvotes: 5

Related Questions