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