Skipping the unwanted branches
Oftentimes there is a need to process nodes selectively, based on conditions
applied to one of the parent nodes. In other words, the condition is checked
against the parent node (control node), and if condition is met, the entire
branch that originates from this node should be processed. Otherwise, children
of this node should be ignored.
Normally, this kind of processing is performed using nested loops and multiple
iterators. The tree iterator allows for doing it in one loop by using its skipChildren()
method. Example below processes only nodes with the specific id (nodes of type "id
" constitutes the second level in the testing XML file).
import com.myarch.treeiterator.TreeIterator;
import com.myarch.treeiterator.DOMAdapter;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
/**
* Demonstrates the selecive traversal using skipChildren .
*
*/
public class SelectiveSkipTraversal {
/**
* Selectively traverses the tree using skipChildren .
* Traverses only the branch of "K.Tamura" and ignores other branches.
*
* @param rootNode root of the DOM tree.
*/
public void traverse ( Node rootNode ) {
// create an iterator.
int idLevel = 2;
TreeIterator tIterator = new TreeIterator ( rootNode, new DOMAdapter());
Node node = null;
while( ( node=(Node)tIterator.next() )!=null ){
// print node information
System.out.println( node.getNodeName()+"="+node.getNodeValue());
if ( tIterator.getDepth() == idLevel && ! (node instanceof Element &&
((Element)node).getAttribute( "id").equalsIgnoreCase("K.TAMURA" ))) {
// allow parsing all children of the node -- applies only to the current node
tIterator.skipChildren();
}
}
}
|