【问题标题】:Remove child nodes from parent - PugiXML从父节点中删除子节点 - PugiXML
【发布时间】:2016-05-25 03:43:51
【问题描述】:
<Node>
  <A>
    <B id = "it_DEN"></B>
  </A>
  <A>
    <B id = "en_KEN"></B>
  </A>
  <A>
    <B id = "it_BEN"></B>
  </A>
</Node>

如何使用 PugiXML 删除具有子节点 &lt;B&gt;&lt;/B&gt; 的子节点 &lt;A&gt;&lt;/A&gt; 的子节点,该子节点的属性 id 不以 it 开头。 结果如下:

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

【问题讨论】:

  • 那你怎么看?你想出了什么方法?
  • 我正在尝试使用 Xpath 搜索我不想要的子节点,然后将其从父节点中删除,但似乎 API 没有那种功能。所以,我想,如果没有其他选择,我会尝试将其全部删除,然后添加所需的子节点。

标签: c++ pugixml


【解决方案1】:

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

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());

【讨论】:

  • 嗨,非常感谢你的帮助,是的,我只是想知道有没有办法用 xpath 来做,非常感谢。
【解决方案2】:

另一种方法是在删除子节点之前递增迭代器。在迭代时移除一个属性。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-23
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多