Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename node/element in boost property tree?

For example I have boost property tree of following structure (created by reading stream with xml or in different way):

<A>
  <B>
    <C></C>
  </B>
</A>

How to rename in existing tree element B to new element with new key: N. So invoking write_xml of this fixed tree should give new xml structure:

<A>
  <N>
    <C></C>
  </N>
</A>

Please present code if it is possible or explain why it is not. Remark: attaching subtree under C to newly generated root is also acceptable but direct renaming in priority.

like image 547
Vlad Novakovsky Avatar asked Oct 22 '25 21:10

Vlad Novakovsky


1 Answers

Well, then, it is possible. Send check for code

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() {
    std::istringstream iss(R"(<A><B><C></C></B></A>)");

    ptree pt;
    read_xml(iss, pt);

    pt.add_child("A.N", pt.get_child("A.B"));
    pt.get_child("A").erase("B");

    write_xml(std::cout, pt);
}

Prints

<?xml version="1.0" encoding="utf-8"?>
<A><N><C/></N></A>
like image 167
sehe Avatar answered Oct 24 '25 09:10

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!