Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost property tree: Remove a nested node

Suppose I have the following tree:

boost::property_tree::ptree tree;
tree.add("1.2.3", "value-1");
tree.add("1.2.3.4", "nested-value");
tree.add("1.2.3", "value-2");
tree.add("1.2.33", "other-value");

which has the following serialized INFO form:

1
{
    2
    {
        3 value-1
        {
            4 nested-value
        }
        3 value-2
        33 other-value
    }
}

Is there a method to remove all nodes having a provided (possibly nested) path? I.e.:

remove(tree, "1.2.3");
BOOST_ASSERT(!tree.get_optional<std::string>("1.2.3") && 
             !tree.get_child_optional("1.2.3"));

with the result INFO form:

1
{
    2
    {
        33 other-value
    }
}

Looking at ptree docs and source code I've found several methods to remove immediate children of a tree (nested children are not accounted). Also, there are several methods to get a subtree by it's full path (even if it is nested). But since there is no way to easily get node's parent, I could not combine all these to get what I need.

Is there any easy way to get what I need, possibly w/o the need to reimplement tree traversal?

like image 451
Alex Che Avatar asked Jun 07 '26 17:06

Alex Che


1 Answers

I don't think it can be done. It would be kind-a ok in JSON, but with INFO subtree keys can be repeated at each level, making it important to traverse all of the tree

Perhaps this answer helps to get started: How to iterate over XML structure in boost::property_tree

Be very careful about iterating a tree that's being modified, though. You will want to double check the iterator invalidation rules in the documentation for erase

like image 179
sehe Avatar answered Jun 10 '26 06:06

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!