How to manually create a boost ptree with XML attributes?

I am using boost libraries to parse XML files and I need to create the ptree manually. I need to add XML attribute to ptree. This is what the acceleration documentation suggests:

ptree pt;
pt.push_back(ptree::value_type("pi", ptree("3.14159")));

      

This adds an element with content, but I also need to add an attribute to the element.

The above code creates:

<pi>3.14</pi>

      

I need to add something like this:

<pi id="pi_0">3.14</pi> 

      

What do I need to change to add the attribute id="pi_0"

?

+3


source to share


1 answer


You are using a "fake" node <xmlattr>

: http://www.boost.org/doc/libs/1_46_1/doc/html/boost_propertytree/parsers.html#boost_propertytree.parsers.xml_parser

Live On Coliru

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

using boost::property_tree::ptree;

int main() {

    ptree pt;
    pt.push_back(ptree::value_type("pi", ptree("3.14159")));
    pt.put("pi.<xmlattr>.id", "pi_0");

    write_xml(std::cout, pt);
}

      



Printing

<?xml version="1.0" encoding="utf-8"?>
<pi id="pi_0">3.14159</pi>

      

+5


source







All Articles