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 = 
    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(
      NodeFilter.SHOW_ELEMENT, null, true);

    traverseLevel(walker, "");

  } catch (Exception ex) {

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