0

我有一些boost::property_tree::ptree。我需要删除具有特定标签名称的一些元素的树。例如,源ptree的 xml 如下:

<?xml version="1.0" encoding="utf-8"?>
<document>
  <B atr="one" atr1="something">
    <to_remove attr="two">10</to_remove>
  </B>
  <to_remove>
    <C>value</C>
    <D>other value</D>
  </to_remove>
  <E>nothing</E>
</document>

我想得到ptree如下的xml:

<?xml version="1.0" encoding="utf-8"?>
<document>
  <B atr="one" atr1="something" />
  <E>nothing</E>
</document>

如何编写函数,生成ptree带有移除<to_remove>节点的新函数?

4

2 回答 2

1

ptree 的 value_type 是 std::pair< const Key, self_type >,所以可以迭代树,移除对应的节点。以下是一个示例。

void remove(ptree &pt){
using namespace boost::property_tree;
    for (auto p = pt.begin(); p != pt.end();){
        if (p->first == "to_remove"){
            p = pt.erase(p);
        }
        else{
            remove(p->second);
            ++p;
        }
    }
}
于 2014-06-16T02:20:55.660 回答
0

更新由于评论替换了我的答案:我建议改为使用适当的 XML 库。

我相信 Boost PropertyTree 在内部使用了修改后的 RapidXml(但它是一个实现细节,所以我不确定我是否会依赖它)。这是我使用PugiXML的看法,它是一个现代的、仅标头的、非验证的 XML 库:

#include <pugixml.hpp>
#include <iostream>

int main()
{
    pugi::xml_document doc;
    doc.load_file("input.txt");

    for (auto& to_remove : doc.select_nodes("descendant-or-self::to_remove/.."))
        while (to_remove.node().remove_child("to_remove"));

    doc.save(std::cout);
}

印刷

<?xml version="1.0"?>
<document>
    <B atr="one" atr1="something" />
    <E>nothing</E>
</document>
于 2014-06-16T06:57:43.237 回答