【问题标题】:Converting Boost ptree node to XML string将 Boost ptree 节点转换为 XML 字符串
【发布时间】:2021-06-14 19:41:46
【问题描述】:

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

如果我有这个 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);

然后我回来了:

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

但我希望得到:

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

我找不到任何如何做到这一点的例子。当然我可以手动重建;我知道元素名称,我应该能够获取所有属性(如果有的话)。这将需要一些处理和字符串连接。

【问题讨论】:

  • “Root”下还有其他孩子。客户要求提供本文档的特定部分,例如“Root.Collection”,我只需要返回该部分。

标签: c++ boost-propertytree writexml


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2011-08-28
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    相关资源
    最近更新 更多