Search code examples
javaxmljakarta-eejaxp

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>

Solution

  • 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);
    }