Javier Buzano
Javier Buzano

Reputation: 103

How to manually create a boost ptree with XML attributes?

I've been using boost libraries to parse XML files and I have to create a ptree manually. I need to add an XML attribute to the ptree. This is what the boost documentation suggests:

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

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

The code above produces:

<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"?

Upvotes: 9

Views: 4020

Answers (1)

sehe
sehe

Reputation: 392929

You use the "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);
}

Prints

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

Upvotes: 11

Related Questions