简体   繁体   English

Boost 属性树:使用指向节点及其父节点的指针删除节点

[英]Boost property tree: Remove a node using pointers to the node and its parent node

I want to remove a node from a ptree which is based on xml:我想从基于 xml 的 ptree 中删除一个节点:

<library>
    <booklist>
        <book id="10">
            <data title="t1"/>
        </book>
        <book id="10">
            <data title="t2"/>
        </book>
        <book id="10">
            <data title="t3"/>
        </book>
        <book id="20">
            <data title="t4"/>
        </book>
    </booklist>
</library>

I have an algorithm to find the right node which returns a pointer to the removing node.我有一个算法来找到正确的节点,该节点返回一个指向删除节点的指针。 Also I have a pointer to the parent of the removing node.我还有一个指向删除节点的父节点的指针。 but the erase() will take an iterator (not a pointer).但是 erase() 将采用迭代器(不是指针)。 My question is how to remove the node using two pointers;我的问题是如何使用两个指针删除节点; a poiter to the removing node and another to the parent node.一个指向移除节点的指针和另一个指向父节点的指针。

void removeElement(const std::string addr, const std::string criteria, boost::property_tree::ptree &ptSource)
{
    boost::property_tree::ptree *ptParent = findParentPTree(addr, criteria, ptSource);   // Points to "library.booklist"
    boost::property_tree::ptree *ptRemove = findRemovePTree(addr, criteria, ptSource);   // eg the third <book> which contains the <data title="t3"/>

    // question: how to remove node ptRemove from ptSource?
}

Note that there are some examples using iterators, but it is not clear how should the iterator of removing node be found.注意这里有一些使用迭代器的例子,但不清楚应该如何找到移除节点的迭代器。

Indeed, there is no direct function to get an iterator from a value reference.实际上,没有直接的函数可以从值引用中获取迭代器。 So you'll have to write it yourself:所以你必须自己写:

In this case it would appear you don't need it to be recursive so it's simpler:在这种情况下,您似乎不需要它是递归的,所以它更简单:

Live On Coliru 住在 Coliru

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

using namespace boost::property_tree;

ptree::iterator child_iterator(ptree& within, ptree const& child) {
    for (auto it = within.begin(); it != within.end(); ++it)
        if (std::addressof(it->second) == std::addressof(child))
            return it;

    return within.end();
}

ptree* findParentPTree(std::string const, std::string const&, ptree const&);
ptree* findRemovePTree(std::string const, std::string const&, ptree const&);

void removeElement(const std::string& addr, const std::string& criteria, ptree &ptSource)
{
    ptree *ptParent = findParentPTree(addr, criteria, ptSource); // Points to "library.booklist"
    ptree *ptRemove = findRemovePTree(addr, criteria, ptSource); // eg the third <book> which contains the <data title="t3"/>

    auto it = child_iterator(*ptParent, *ptRemove);
    if (it != ptParent->end())
        ptParent->erase(it);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM