我想从基于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?
}
请注意,有一些使用迭代器的示例,但不清楚如何找到删除节点的迭代器。
答案 0 :(得分:1)
实际上,没有直接函数从值引用中获取迭代器。因此,您必须自己编写:
在这种情况下,您似乎不需要递归,所以它更简单:
<强> Live On 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);
}