Quitar nodos de QDom
Frecuentes
Visto 2,564 equipos
1
I am trying to remove all the nodes in my .xml. However, with the following codes, I could only remove the first and third nodes, leaving the second node unable to be removed. I figured out that something is wrong with my for loop, but I am unable to determine what went wrong. It seemed to skip the removing of the second node.
Alguien puede ayudarme porfavor? Gracias.
malfunctions.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);
}
}
...
Resultados:
<InjectedMalfunctions>
<Malfunction>
<Name>ABC2</Name>
<Time>01:00:00</Time>
</Malfunction>
</InjectedMalfunctions>
1 Respuestas
9
QDomNodeList
is a live list.
From the docs: 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.
It skips the second node because you add 1 to your i
variable, while at the same time you remove a node.
Primer bucle:
nodes[Node1, Node2, Node3]
i = 0
remove nodes[0] (Node1)
Segundo bucle:
nodes[Node2, Node3]
i = 1
remove nodes[1] (Node3)
After this your loop finishes. Try making a while
loop that checks if the nodes
list is empty, and remove the first node of the list:
while(!nodes.isEmpty())
{
QDomNode node = nodes.at(0);
node.parentNode().removeChild(node);
}
Respondido 12 Feb 14, 07:02
Thanks @thuga. Changing into a while loop that always remove the first node, worked. I didn't know it was a live list. Therefore, I kept missing the "second" node. - Wallace