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

vin*_*001 2 c++ pugixml

<Node>
  <A>
    <B id = "it_DEN"></B>
  </A>
  <A>
    <B id = "en_KEN"></B>
  </A>
  <A>
    <B id = "it_BEN"></B>
  </A>
</Node>
Run Code Online (Sandbox Code Playgroud)

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

<Node>
  <A>
    <B id = "it_DEN"></B>
  </A>
  <A>
    <B id = "it_BEN"></B>
  </A>
</Node>
Run Code Online (Sandbox Code Playgroud)

zeu*_*xcg 6

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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