Removing DOM nodes when traversing a NodeList

Viewed 30387

I'm about to delete certain elements in an XML document, using code like the following:

NodeList nodes = ...;
for (int i = 0; i < nodes.getLength(); i++) {
  Element e = (Element)nodes.item(i);
  if (certain criteria involving Element e) {
    e.getParentNode().removeChild(e);
  }
}

Will this interfere with proper traversal of the NodeList? Any other caveats with this approach? If this is totally wrong, what's the proper way to do it?

8 Answers

As already mentioned, removing an element reduces the size of the list but the counter is still increasing (i++):

[element 1] <- Delete 
[element 2]
[element 3]
[element 4]
[element 5]

[element 2]  
[element 3] <- Delete
[element 4]
[element 5]
--

[element 2]  
[element 4] 
[element 5] <- Delete
--
--

[element 2]  
[element 4] 
--
--
--

The simplest solution, in my opinion, would be to remove i++ section in the loop and do it as needed when the iterated element was not deleted.

NodeList nodes = ...;
for (int i = 0; i < nodes.getLength();) {
  Element e = (Element)nodes.item(i);
  if (certain criteria involving Element e) {
    e.getParentNode().removeChild(e);        
  } else {
    i++;
  }
}

Pointer stays on the same place when the iterated element was deleted. The list shifts by itself.

[element 1] <- Delete 
[element 2]
[element 3]
[element 4]
[element 5]

[element 2] <- Leave
[element 3]
[element 4]
[element 5]
--

[element 2] 
[element 3] <- Leave
[element 4]
[element 5]
--

[element 2] 
[element 3] 
[element 4] <- Delete
[element 5]
--

[element 2] 
[element 3] 
[element 5] <- Delete
--
--

[element 2] 
[element 3] 
--
--
--

At the end, you must update the XML file within the path of your project.

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
DOMSource source = new DOMSource(documentoXml);
StreamResult result = new StreamResult(new File(path + "\\resources\\xml\\UsuariosFile.xml"));
transformer.transform(source, result);

if you do not put these lines, your file will not be updated

Related