Search code examples
c++boostboost-propertytree

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.


Solution

  • 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>