2

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.

M.K.
  • 159
  • 8
  • There are other children under "Root". A client asks for a specific section of this document, e.g. "Root.Collection" and I have to return that section only. – M.K. Jun 14 '21 at 20:10

1 Answers1

0

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);
lubgr
  • 37,368
  • 3
  • 66
  • 117