Demo Tree Walker : XML Tree « XML « Java






Demo Tree Walker

Demo Tree Walker
  

/*
  Java, XML, and Web Services Bible
  Mike Jasnowski
  ISBN: 0-7645-4847-6
*/
import org.apache.xerces.parsers.DOMParser;
import org.xml.sax.SAXException;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import java.io.IOException;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.TreeWalker;


public class DemoTreeWalker {

     public static void main(String args[]) throws SAXException,IOException{
       
      DOMParser parser = new DOMParser();
      parser.parse("games.xml");

      Document doc = parser.getDocument();
              
      DocumentTraversal docTraversal = (DocumentTraversal)doc;
              
      TreeWalker iter =
                  docTraversal.createTreeWalker(doc.getDocumentElement(),
                              NodeFilter.SHOW_ALL,                                                 
                              null,
                             false);
       Node n = null;
       while ((n=iter.nextNode())!=null){
           System.out.println("Node name: " +
                               n.getNodeName());
           System.out.println("Node value: " +
                               n.getNodeValue());
       }
              
    }
}
//game.xml
/*
<?xml version="1.0"?>
<games>
<game genre="shooter">XML Invaders</game>
<game genre="rpg">A Node in the XPath</game>
<game genre="action">XPath Racers</game>
</games>
*/

           
         
    
  








Related examples in the same category

1.XML Tree: Simple XML utility class
2.A simple XML parser that builds a tree from SAX eventsA simple XML parser that builds a tree from SAX events
3.DOM Tree Walker Tree Model
4.XML Tree ViewXML Tree View
5.SAX Tree ViewerSAX Tree Viewer
6.Enter every DOM node into a Swing JTree tree. The forward and backward mappings between Nodes to TreeNodes are kept.
7.This program displays an XML document as a tree