Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pruning DOM Document

Status
Not open for further replies.

toolkit

Programmer
Aug 5, 2001
771
GB
I was wondering if any Java/XML gurus could help me out here. I wish to remove a subset of <item> elements from a Document, using code similar to:
Code:
  public static void pruneDocument( Document document, ItemFilter filter ) {
    NodeList items = document.getElementsByTagName( &quot;item&quot; );
    for ( int i = 0; i < items.getLength(); i++ ) {
      Node node = items.item(i);
      Node parent = node.getParentNode();
      if( !filter.accept( (Element)node ) )
        parent.removeChild( node );
    }
  }
However, in removing a child, I believe the NodeList gets updated, so that [tt]items.item(i)[/tt] skips over an item that has been shifted down? I made a simple filter which always returns false, and this produced a Document where each alternate <item> element was successfully removed. How should I approach removing these elements?
Thanks for any advice, Neil
 
Looks like I can use a TreeWalker, or NodeIterator instead. But could someone explain if I can use this filtered view when serializing, or if I have to actually prune the document before serializing?
Thanks, Neil
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top