Traversing a DOM tree using a TreeWalker in Java

(DOM Level 2!) TreeWalker allows you to navigate a DOM tree. You can specify the view on the tree with whatToShow flags and a NodeFilter (for an example on using a NodeFilter, check out How do I traverse a DOM tree using a NodeIterator).

Once you have a TreeWalker instance, you can navigate through the structure using various methods that speak for themselves. Check out the API docs for more information: TreeWalker, NodeFilter.

customers.xml (!!remove the space between ? and xml):

<? xml version="1.0" encoding="UTF-8"?>
<customers>
   <customer id="C12345">
      <name>Joris Van den Bogaert</name>
      <address>
         <addressline>Handelskaai 3</addressline>
         <zip>1000</zip>
         <location>Brussels</location>
         <country>BELGIUM</country>
      </address>
   </customer>
   <customer id="C23495">
      <name>John Doe</name>
      <address>
         <addressline>5, S 5th Ave.</addressline>
         <zip>59715</zip>
         <location>Bozeman, MT</location>
         <country>US</country>
      </address>
   </customer>
   <customer id="C03429">
      <name>John Babcock</name>
      <address>
         <addressline>73, Broad street</addressline>
         <zip>06418</zip>
         <location>Chester, CT</location>
         <country>US</country>
      </address>
   </customer>
   <customer id="C12345">
      <name>Dominique Bodard</name>
      <address>
         <addressline>21-23, Rue de Madrid</addressline>
         <zip>75008</zip>
         <location>Paris</location>
         <country>FRANCE</country>
      </address>
   </customer>
</customers>

Main.java:

import org.w3c.dom.*;
import org.w3c.dom.traversal.*;
  
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
 
import java.io.*;
   
public class Main
{
   public static void main(String []args) {
      Document doc;
  
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File("customers.xml")); 
 
         if (!doc.isSupported("Traversal", "2.0")) {
            System.out.println("Traversal not supported in your parser version");
            System.exit(1);
         }
 
         DocumentTraversal dt = (DocumentTraversal) doc;
         TreeWalker walker = dt.createTreeWalker(doc, 
                                                 NodeFilter.SHOW_ALL, 
                                                 null, 
                                                 true);
  
         outputNode(walker.getCurrentNode());  // #document
         outputNode(walker.nextNode());        // customers
         outputNode(walker.nextNode());        // #text
         outputNode(walker.nextNode());        // customer
         outputNode(walker.nextNode());        // #text
         outputNode(walker.nextNode());        // name
         outputNode(walker.lastChild());       // #text [Joris Van den Bogaert]
         outputNode(walker.nextNode());        // #text
         outputNode(walker.nextNode());        // address
         outputNode(walker.previousSibling()); // #text
         outputNode(walker.nextNode());        // address
         outputNode(walker.nextNode());        // #text
         outputNode(walker.parentNode());      // address
         outputNode(walker.nextNode());        // #text
         outputNode(walker.nextSibling());     // addressline
         outputNode(walker.nextNode());        // #text [Handelskaai 3]
         outputNode(walker.previousNode());    // addressline
         outputNode(walker.parentNode());      // address
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
 
   public static void outputNode(Node node) {
      System.out.print(node.getNodeName());
      if (node.getNodeType() == Node.TEXT_NODE && !node.getNodeValue().trim().equals("")) {
         System.out.print(" [" + node.getNodeValue() + "]");
      }
      System.out.println();
   } 
}

outputs:

#document
customers
#text
customer
#text
name
#text [Joris Van den Bogaert]
#text
address
#text
address
#text
address
#text
addressline
#text [Handelskaai 3]
addressline
address