Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removeChild() method is breaking for loop

I am using following code to remove multiple elements from XMl file.

NodeList removeNodeList = doc.getElementsByTagName("server1");
Element rootElement = doc.getDocumentElement();

for (int i = 0; i < removeNodeList.getLength(); i++) {
    rootElement.removeChild(removeNodeList.item(i));
}

But after removing one element it is coming out of loop. What is the issue.

Following is my XML file content.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<start>

    <category name="server1"/>
    <category name="server2"/>

    <server1 name="serverName1" value="serverValue"/>
    <server1 name="serverName1" value="serverValue"/>

    <server2 name="serverName2" value="serverValue"/>

</start>
like image 874
Vishrant Avatar asked Feb 11 '26 06:02

Vishrant


1 Answers

I found the solution:

Let me explain what was the problem in detail.

NodeList removeNodeList = doc.getElementsByTagName("server1"); removeNodeList.getLength() will return 2 as there are 2 nodes with nodeName server1 then after executing rootElement.removeChild(removeNodeList.item(i)); and then checking for loop condition i.e. the value of i is 1 and removeNodeList.getLength() returns 1 as now only 1 node with nodeName server1 is remaining in DOM document and this condition was failing as 1 < 1 is false

So I followed the following approach:

Delete all the elements afterwards once the NodeList is no longer used.

NodeList nodes = doc.getElementsByTagName(elementName);
Set<Element> targetElements = new HashSet<Element>();

for (int i = 0; i < nodes.getLength(); i++) {
    Element e = (Element)nodes.item(i);
    targetElements.add(e);
}
for (Element e: targetElements) {
    e.getParentNode().removeChild(e);
}
like image 113
Vishrant Avatar answered Feb 17 '26 22:02

Vishrant