gpt4 book ai didi

c++ - 从父节点中删除子节点 - PugiXML

转载 作者:行者123 更新时间:2023-11-27 22:50:44 27 4
gpt4 key购买 nike

<Node>
<A>
<B id = "it_DEN"></B>
</A>
<A>
<B id = "en_KEN"></B>
</A>
<A>
<B id = "it_BEN"></B>
</A>
</Node>

如何删除 <A></A> 的子节点有子节点 <B></B>具有属性 id不是以 it 开头 使用 PugiXML。结果如下:

<Node>
<A>
<B id = "it_DEN"></B>
</A>
<A>
<B id = "it_BEN"></B>
</A>
</Node>

最佳答案

如果您想在迭代时删除节点(以保持代码单次通过),这会有点棘手。这是一种方法:

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

或者,您可以只使用 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());

关于c++ - 从父节点中删除子节点 - PugiXML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37427435/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com