How to manually create a boost ptree with XML attributes?
Asked Answered
O

1

9

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

Odelsting answered 22/7, 2015 at 16:51 Comment(0)
T
11

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>
Tanishatanitansy answered 22/7, 2015 at 18:31 Comment(1)
Note the documentation link :) Boost documentation is frequently terse, but patient.Tanishatanitansy

© 2022 - 2024 — McMap. All rights reserved.