|
How to traverse the DOM tree using TreeWalker |
|
|
DOM interface offers a nice tool for browsing the tree. This is
a TreeWalker interface. It allows to performs filtering on the node-flow,
convenient navigation and saving current position for the following return.
Example application below shows to traverse DOM-tree on element only
using TreeWalker:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.TreeWalker;
import org.w3c.dom.*;
/**
* This sample program using tree-walker for
* non-linear traverse of DOM-document.
*/
public class Test {
public static void main(String[] args) {
try {
// load the document from a file:
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder loader = factory.newDocumentBuilder();
Document document = loader.parse("sample.xml");
// this cast is checked on Apache implementation (Xerces):
DocumentTraversal traversal = (DocumentTraversal) document;
TreeWalker walker = traversal.createTreeWalker(
document.getDocumentElement(),
NodeFilter.SHOW_ELEMENT, null, true);
traverseLevel(walker, "");
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static final void traverseLevel(TreeWalker walker,
String indent) {
// describe current node:
Node parend = walker.getCurrentNode();
System.out.println(indent + "- " +
((Element) parend).getTagName());
// traverse children:
for (Node n = walker.firstChild(); n != null;
n = walker.nextSibling()) {
traverseLevel(walker, indent + '\t');
}
// return position to the current (level up):
walker.setCurrentNode(parend);
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.