c++boost-propertytreewritexml

Converting Boost ptree node to XML string


I am using boost (version 1.70.0) property tree. Is there a way to convert a node to XML string including the node itself, not just node's children?

If I have this XML:

<Root>
  <SomeOtherElement>..</SomeOtherElement>
  <Collection>
     <Item Attr1=".." attr2="" />
     <Item Attr1=".." attr2="" />
  </Collection>
</Root>
auto node = pt.get_child("Root.Collection");
std::ostringstream os;
write_xml(os, node);

Then I get back:

<Item Attr1=".." attr2="" />
<Item Attr1=".." attr2="" />

But I expect to get:

<Collection>
     <Item Attr1=".." attr2="" />
     <Item Attr1=".." attr2="" />
</Collection>

I could not find any example of how to do it. Of cause I can manually reconstruct; I know the element name and I should be able to grab all attributes (if any). That would require some processing and string concatenation.


Solution

  • You can create a helper property tree to hold nothing but the extracted one. This involves some additional copying, but should otherwise work just fine:

    auto node = pt.get_child("Root.Collection");
    
    ptree extraction{};
    extraction.put_child("Root.Collection", node);
    
    boost::property_tree::write_xml(std::cout, extraction);