C++ 从父-PugiXML中删除子节点
如果您想在迭代时删除节点(以保持代码的单次传递),这有点棘手。这里有一种方法:C++ 从父-PugiXML中删除子节点,c++,pugixml,C++,Pugixml,如果您想在迭代时删除节点(以保持代码的单次传递),这有点棘手。这里有一种方法: <Node> <A> <B id = "it_DEN"></B> </A> <A> <B id = "it_BEN"></B> </A> </Node> 或者,您可以只使用XPath并删除结果: bool should_remove(pugi::xml_node n
<Node>
<A>
<B id = "it_DEN"></B>
</A>
<A>
<B id = "it_BEN"></B>
</A>
</Node>
或者,您可以只使用XPath并删除结果:
bool should_remove(pugi::xml_node node)
{
const char* id = node.child("B").attribute("id").value();
return strncmp(id, "it_", 3) != 0;
}
for (pugi::xml_node child = doc.child("Node").first_child(); child; )
{
pugi::xml_node next = child.next_sibling();
if (should_remove(child))
child.parent().remove_child(child);
child = next;
}
另一种方法是在删除子项之前增加迭代器。在迭代时删除属性
pugi::xpath_node_set ns = doc.select_nodes("/Node/A[B[not(starts-with(@id, 'it_'))]]");
for (auto& n: ns)
n.node().parent().remove_child(n.node());
那你觉得呢?你想出了什么方法?我试图使用Xpath搜索我不想要的子节点,然后将其从父节点中删除,但API似乎没有这种功能。所以,我想,如果没有其他选择,我会尝试将其全部删除,然后再添加所需的子节点。您好,非常感谢您的帮助,是的,我只是想知道是否有一种方法可以使用xpath来完成,非常感谢。
pugi::xpath_node_set ns = doc.select_nodes("/Node/A[B[not(starts-with(@id, 'it_'))]]");
for (auto& n: ns)
n.node().parent().remove_child(n.node());
for(pugi::xml_attribute_iterator it = node.attributes_begin(); it != node.attributes_end();){
pugi::xml_attribute attr = *it++;
if(should_remove(attr)){
node.remove_attribute(attr);
}
}