Removing DOM nodes when traversing a NodeList

前端 未结 7 788
南方客
南方客 2020-12-06 04:54

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++)         


        
相关标签:
7条回答
  • 2020-12-06 05:45

    So, given that removing nodes while traversing the NodeList will cause the NodeList to be updated to reflect the new reality, I assume that my indices will become invalid and this will not work.

    So, it seems the solution is to keep track of the elements to delete during the traversal, and delete them all afterward, once the NodeList is no longer used.

    NodeList nodes = ...;
    Set<Element> targetElements = new HashSet<Element>();
    for (int i = 0; i < nodes.getLength(); i++) {
      Element e = (Element)nodes.item(i);
      if (certain criteria involving Element e) {
        targetElements.add(e);
      }
    }
    for (Element e: targetElements) {
      e.getParentNode().removeChild(e);
    }
    
    0 讨论(0)
提交回复
热议问题