根据 Pugixml 中的子值删除节点

Deleting a node based on child value in Pugixml

本文关键字:删除 节点 Pugixml 根据      更新时间:2023-10-16

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

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 条件来检查子节点值是否匹配,但如果可能的话,我想通过查询来做到这一点?

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

从本质上讲,它更改了相关实际节点的名称。之后,它运行一个查询(其节点集可以在 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");