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

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

本文关键字:节点 父节点 删除 指针 属性      更新时间:2023-10-16

我想从基于 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>

我有一种算法可以找到正确的节点,该节点返回指向删除节点的指针。我还有一个指向删除节点父节点的指针。但是 erase() 将采用迭代器(而不是指针)。我的问题是如何使用两个指针删除节点;一个指向移除节点的 poiter,另一个指向父节点。

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

请注意,有一些使用迭代器的示例,但不清楚应该如何找到删除节点的迭代器。

实际上,没有直接函数可以从值引用中获取迭代器。所以你必须自己写:

  • C++:提升 ptree 相对键

在这种情况下,您似乎不需要它是递归的,因此更简单:

住在科里鲁

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