首页 > 解决方案 > 根据 Pugixml 中的子值删除节点

问题描述

到目前为止,我可以删除我要删除的实际节点的所有子节点,但不能删除节点本身。

pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file("config/config.xml");
pugi::xpath_query query_network_last_run("//state[network/network_last_run='2']");
pugi::xpath_node_set network_last_run = query_network_last_run.evaluate_node_set(doc);

下面的部分删除了特定部分——但我想删除基于子值 (network_last_run)的网络,而不是它的这个子值。

network_last_run[0].node().remove_child("network_gateway");

XML文件结构

<root>
 <state>
  <network>
   <network_last_run>2<network_last_run>
   <network_gateway>192.168.3.1</network_gateway>
  </network>
 </state>
</root>

我尝试使用

network_last_run[0].node().parent().remove_child("network");

但似乎只修改了存储在内存中的实际结构(删除第一个),而不是查询的结构。

我可能可以在 for 循环中执行此操作并使用 if 条件来检查子节点值是否匹配,但如果可能的话,我想通过查询来做到这一点?

标签: c++xmlxml-parsingpugixml

解决方案


在玩了一下之后,这就是我提出的解决方案(我在其他任何地方都找不到答案,所以我想我可以在这里发布)

从本质上讲,它会更改相关实际节点的名称。之后,它运行一个查询(其节点集可以在 for 循环中使用)并删除任何具有新名称的子元素。

network_last_run[0].node().set_name("removal");



pugi::xpath_query query_removals("//state");
pugi::xpath_node_set removals = query_removals.evaluate_node_set(doc);

removals[0].node().remove_child("removal");

推荐阅读