Is there a convenient way to erase a node from a property tree, preserving its child nodes?

南楼画角 提交于 2019-11-30 18:27:57

问题


I want to delete a node from a boost property tree, but I want to preserve its children and connect them to the parent of the deleted node (i.e. to their grandparent node). Is there an elegant way to achieve this?


回答1:


This might be the most efficient way to move the grandchildren:

std::move(middle.begin(), middle.end(), back_inserter(parent));

Full sample

Live On Coliru

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;

int main() {

    std::istringstream iss(R"({ "a" : { "middle" : { "a1":1, "a2":2, "a3":3 }, "more":"stuff" } })");
    ptree pt;
    read_json(iss, pt);

    auto& parent = pt.get_child("a");
    auto& middle = pt.get_child("a.middle");

    std::move(middle.begin(), middle.end(), back_inserter(parent));
    parent.erase("middle");

    write_json(std::cout, pt);

}

Sample json output:

{
    "a": {
        "more": "stuff",
        "a1": "1",
        "a2": "2",
        "a3": "3"
    }
}



回答2:


I had to do something similar.

I used an iterator with recursion and copied the child before removing the node and branching it back on a newly created one.

But I guess the full copy of each trees before removing to be quite resources-consuming so you can only do it with relatively small trees and it isn't really elegant.



来源:https://stackoverflow.com/questions/29561852/is-there-a-convenient-way-to-erase-a-node-from-a-property-tree-preserving-its-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!