gpt4 book ai didi

c++ - QDom 删除节点

转载 作者:太空宇宙 更新时间:2023-11-03 10:29:15 25 4
gpt4 key购买 nike

我正在尝试删除 .xml 中的所有节点。但是,使用以下代码,我只能删除第一个和第三个节点,而无法删除第二个节点。我发现我的 for 循环有问题,但我无法确定出了什么问题。它似乎跳过了第二个节点的删除。

有人可以帮忙吗?谢谢。

故障.xml:

<InjectedMalfunctions>
<Malfunction>
<Name>ABC1</Name>
<Time>00:00:00</Time>
</Malfunction>
<Malfunction>
<Name>ABC2</Name>
<Time>01:00:00</Time>
</Malfunction>
<Malfunction>
<Name>ABC3</Name>
<Time>03:00:00</Time>
</Malfunction>
</InjectedMalfunctions>

.cpp:

QFile inFile("C:/Test/malfunctions.xml");
inFile.open(IODevice::ReadOnly | QIODevice::Text);
QDomDocument doc;
doc.setContent(&inFile);
inFile.close();

QDomNodeList nodes = doc.elementsbyTagName("Malfunction");
if(!nodes.isEmpty())
{
for(int i = 0; i < nodes.count(); ++i)
{
QDomNode node = nodes.at(i);
node.parentNode().removeChild(node);
}
}

...

结果:

<InjectedMalfunctions>
<Malfunction>
<Name>ABC2</Name>
<Time>01:00:00</Time>
</Malfunction>
</InjectedMalfunctions>

最佳答案

QDomNodeList 是一个实时列表。来自文档:The Document Object Model (DOM) requires these lists to be "live": whenever you change the underlying document, the contents of the list will get updated.

它会跳过第二个节点,因为您将 1 添加到您的 i 变量,同时您删除了一个节点。

第一个循环:

nodes[Node1, Node2, Node3]
i = 0
remove nodes[0] (Node1)

第二个循环:

nodes[Node2, Node3]
i = 1
remove nodes[1] (Node3)

在此之后,您的循环结束。尝试制作一个 while 循环来检查 nodes 列表是否为空,并删除列表的第一个节点:

while(!nodes.isEmpty())
{
QDomNode node = nodes.at(0);
node.parentNode().removeChild(node);
}

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

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