Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 549
Javier Buzano Avatar asked Jul 22 '15 16:07

Javier Buzano


1 Answers

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>
like image 191
sehe Avatar answered Oct 17 '22 14:10

sehe