如何从Boost.PropertyTree复制子树

时间:2014-06-16 01:24:17

标签: c++ boost boost-propertytree subtree

我有一些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>

2 个答案:

答案 0 :(得分:1)

ptree的value_type是std :: pair&lt; const键,self_type&gt;,因此您可以迭代树并删除相应的节点。以下是一个示例。

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;
        }
    }
}

答案 1 :(得分: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>
相关问题