将 Boost ptree 节点转换为 XML 字符串

问题描述

我正在使用 boost(版本 1.70.0)属性树。有没有办法将节点转换为 XML 字符串,包括节点本身,而不仅仅是节点的子节点?

如果我有这个 XML:

Route
<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);

但我希望得到:

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

我找不到任何有关如何执行此操作的示例。因为我可以手动重建;我知道元素名称,我应该能够获取所有属性(如果有)。这需要一些处理和字符串连接。

解决方法

您可以创建一个辅助属性树,只保存提取的属性树。这涉及一些额外的复制,但应该可以正常工作:

auto node = pt.get_child("Root.Collection");

ptree extraction{};
extraction.put_child("Root.Collection",node);

boost::property_tree::write_xml(std::cout,extraction);