Java/XML/XML Tree

Материал из Java эксперт
Перейти к: навигация, поиск

A simple XML parser that builds a tree from SAX events

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// VSX.java //A simple XML parser that builds a tree from SAX events. // import java.io.File; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class VSX {

 public TreeModel parse(String filename) {
   SAXParserFactory factory = SAXParserFactory.newInstance();
   XMLTreeHandler handler = new XMLTreeHandler();
   try {
     // Parse the input.
     SAXParser saxParser = factory.newSAXParser();
     saxParser.parse(new File(filename), handler);
   } catch (Exception e) {
     System.err.println("File Read Error: " + e);
     e.printStackTrace();
     return new DefaultTreeModel(new DefaultMutableTreeNode("error"));
   }
   return new DefaultTreeModel(handler.getRoot());
 }
 public static class XMLTreeHandler extends DefaultHandler {
   private DefaultMutableTreeNode root, currentNode;
   public DefaultMutableTreeNode getRoot() {
     return root;
   }
   // SAX Parser Handler methods...
   public void startElement(String namespaceURI, String lName,
       String qName, Attributes attrs) throws SAXException {
     String eName = lName; // Element name
     if ("".equals(eName))
       eName = qName;
     Tag t = new Tag(eName, attrs);
     DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(t);
     if (currentNode == null) {
       root = newNode;
     } else {
       // Must not be the root node...
       currentNode.add(newNode);
     }
     currentNode = newNode;
   }
   public void endElement(String namespaceURI, String sName, String qName)
       throws SAXException {
     currentNode = (DefaultMutableTreeNode) currentNode.getParent();
   }
   public void characters(char buf[], int offset, int len)
       throws SAXException {
     String s = new String(buf, offset, len).trim();
     ((Tag) currentNode.getUserObject()).addData(s);
   }
 }
 public static class Tag {
   private String name;
   private String data;
   private Attributes attr;
   public Tag(String n, Attributes a) {
     name = n;
     attr = a;
   }
   public String getName() {
     return name;
   }
   public Attributes getAttributes() {
     return attr;
   }
   public void setData(String d) {
     data = d;
   }
   public String getData() {
     return data;
   }
   public void addData(String d) {
     if (data == null) {
       setData(d);
     } else {
       data += d;
     }
   }
   public String getAttributesAsString() {
     StringBuffer buf = new StringBuffer(256);
     for (int i = 0; i < attr.getLength(); i++) {
       buf.append(attr.getQName(i));
       buf.append("=\"");
       buf.append(attr.getValue(i));
       buf.append("\"");
     }
     return buf.toString();
   }
   public String toString() {
     String a = getAttributesAsString();
     return name + ": " + a + (data == null ? "" : " (" + data + ")");
   }
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("VSX Test");
   VSX parser = new VSX();
   JTree tree = new JTree(parser.parse("build.xml"));
   frame.getContentPane().add(new JScrollPane(tree));
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(300, 400);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Demo Tree Walker

   <source lang="java">

/*

 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>

  • /


 </source>
   
  
 
  



DOM Tree Walker Tree Model

   <source lang="java">

/*

* Copyright (c) 2000 David Flanagan.  All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book (recommended),
* visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.w3c.dom.traversal.DocumentTraversal; import org.w3c.dom.traversal.NodeFilter; import org.w3c.dom.traversal.TreeWalker; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.apache.xerces.internal.parsers.DOMParser; /**

* This class implements the Swing TreeModel interface so that the DOM tree
* returned by a TreeWalker can be displayed in a JTree component.
*/

public class DOMTreeWalkerTreeModel implements TreeModel {

 TreeWalker walker; // The TreeWalker we"re modeling for JTree
 /** Create a TreeModel for the specified TreeWalker */
 public DOMTreeWalkerTreeModel(TreeWalker walker) {
   this.walker = walker;
 }
 /**
  * Create a TreeModel for a TreeWalker that returns all nodes in the
  * specified document
  */
 public DOMTreeWalkerTreeModel(Document document) {
   DocumentTraversal dt = (DocumentTraversal) document;
   walker = dt
       .createTreeWalker(document, NodeFilter.SHOW_ALL, null, false);
 }
 /**
  * Create a TreeModel for a TreeWalker that returns the specified element
  * and all of its descendant nodes.
  */
 public DOMTreeWalkerTreeModel(Element element) {
   DocumentTraversal dt = (DocumentTraversal) element.getOwnerDocument();
   walker = dt.createTreeWalker(element, NodeFilter.SHOW_ALL, null, false);
 }
 // Return the root of the tree
 public Object getRoot() {
   return walker.getRoot();
 }
 // Is this node a leaf? (Leaf nodes are displayed differently by JTree)
 public boolean isLeaf(Object node) {
   walker.setCurrentNode((Node) node); // Set current node
   Node child = walker.firstChild(); // Ask for a child
   return (child == null); // Does it have any?
 }
 // How many children does this node have?
 public int getChildCount(Object node) {
   walker.setCurrentNode((Node) node); // Set the current node
   // TreeWalker doesn"t count children for us, so we count ourselves
   int numkids = 0;
   Node child = walker.firstChild(); // Start with the first child
   while (child != null) { // Loop "till there are no more
     numkids++; // Update the count
     child = walker.nextSibling(); // Get next child
   }
   return numkids; // This is the number of children
 }
 // Return the specified child of a parent node.
 public Object getChild(Object parent, int index) {
   walker.setCurrentNode((Node) parent); // Set the current node
   // TreeWalker provides sequential access to children, not random
   // access, so we"ve got to loop through the kids one by one
   Node child = walker.firstChild();
   while (index-- > 0)
     child = walker.nextSibling();
   return child;
 }
 // Return the index of the child node in the parent node
 public int getIndexOfChild(Object parent, Object child) {
   walker.setCurrentNode((Node) parent); // Set current node
   int index = 0;
   Node c = walker.firstChild(); // Start with first child
   while ((c != child) && (c != null)) { // Loop "till we find a match
     index++;
     c = walker.nextSibling(); // Get the next child
   }
   return index; // Return matching position
 }
 // Only required for editable trees; unimplemented here.
 public void valueForPathChanged(TreePath path, Object newvalue) {
 }
 // This TreeModel never fires any events (since it is not editable)
 // so event listener registration methods are left unimplemented
 public void addTreeModelListener(TreeModelListener l) {
 }
 public void removeTreeModelListener(TreeModelListener l) {
 }
 /**
  * This main() method demonstrates the use of this class, the use of the
  * Xerces DOM parser, and the creation of a DOM Level 2 TreeWalker object.
  */
 public static void main(String[] args) throws IOException, SAXException {
   // Obtain an instance of a Xerces parser to build a DOM tree.
   // Note that we are not using the JAXP API here, so this
   // code uses Apache Xerces APIs that are not standards
   DOMParser parser = new org.apache.xerces.parsers.DOMParser();
   // Get a java.io.Reader for the input XML file and
   // wrap the input file in a SAX input source
   Reader in = new BufferedReader(new FileReader(args[0]));
   InputSource input = new org.xml.sax.InputSource(in);
   // Tell the Xerces parser to parse the input source
   parser.parse(input);
   // Ask the parser to give us our DOM Document. Once we"ve got the DOM
   // tree, we don"t have to use the Apache Xerces APIs any more; from
   // here on, we use the standard DOM APIs
   Document document = parser.getDocument();
   // If we"re using a DOM Level 2 implementation, then our Document
   // object ought to implement DocumentTraversal
   DocumentTraversal traversal = (DocumentTraversal) document;
   // For this demonstration, we create a NodeFilter that filters out
   // Text nodes containing only space; these just clutter up the tree
   NodeFilter filter = new NodeFilter() {
     public short acceptNode(Node n) {
       if (n.getNodeType() == Node.TEXT_NODE) {
         // Use trim() to strip off leading and trailing space.
         // If nothing is left, then reject the node
         if (((Text) n).getData().trim().length() == 0)
           return NodeFilter.FILTER_REJECT;
       }
       return NodeFilter.FILTER_ACCEPT;
     }
   };
   // This set of flags says to "show" all node types except comments
   int whatToShow = NodeFilter.SHOW_ALL & ~NodeFilter.SHOW_COMMENT;
   // Create a TreeWalker using the filter and the flags
   TreeWalker walker = traversal.createTreeWalker(document, whatToShow,
       filter, false);
   // Instantiate a TreeModel and a JTree to display it
   JTree tree = new JTree(new DOMTreeWalkerTreeModel(walker));
   // Create a frame and a scrollpane to display the tree, and pop them up
   JFrame frame = new JFrame("DOMTreeWalkerTreeModel Demo");
   frame.getContentPane().add(new JScrollPane(tree));
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   
   frame.setSize(500, 250);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Enter every DOM node into a Swing JTree tree. The forward and backward mappings between Nodes to TreeNodes are kept.

   <source lang="java">
 

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.Serializable; import java.util.Hashtable; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreeNode; import org.w3c.dom.Attr; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Notation; /**

* DOMTree class to enter every DOM node into a Swing JTree tree. The forward
* and backward mappings between Nodes to TreeNodes are kept.
* 
* @version $Id: DOMTreeFull.java 447689 2006-09-19 02:40:36Z mrglavas $
*/

public class DOMTreeFull extends JTree {

 private static final long serialVersionUID = 3978144335541975344L;
 //
 // Constructors
 //
 /** Default constructor. */
 public DOMTreeFull() {
   this(null);
 }
 /** Constructs a tree with the specified document. */
 public DOMTreeFull(Node root) {
   super(new Model());
   // set tree properties
   setRootVisible(false);
   // set properties
   setRootNode(root);
 } // <init>()
 //
 // Public methods
 //
 /** Sets the root. */
 public void setRootNode(Node root) {
   ((Model) getModel()).setRootNode(root);
   expandRow(0);
 }
 /** Returns the root. */
 public Node getRootNode() {
   return ((Model) getModel()).getRootNode();
 }
 /** get the org.w3c.Node for a MutableTreeNode. */
 public Node getNode(Object treeNode) {
   return ((Model) getModel()).getNode(treeNode);
 }
 /** get the TreeNode for the org.w3c.Node */
 public TreeNode getTreeNode(Object node) {
   return ((Model) getModel()).getTreeNode(node);
 }
 //
 // Classes
 //
 /**
  * DOM tree model.
  * 
  */
 public static class Model extends DefaultTreeModel implements Serializable {
   private static final long serialVersionUID = 3258131375181018673L;
   //
   // Data
   //
   /** Root. */
   private Node root;
   /** Node Map. */
   private Hashtable nodeMap = new Hashtable();
   /** Tree Node Map. */
   private Hashtable treeNodeMap = new Hashtable();
   //
   // Constructors
   //
   /** Default constructor. */
   public Model() {
     this(null);
   }
   /** Constructs a model from the specified root. */
   public Model(Node node) {
     super(new DefaultMutableTreeNode());
     if (node != null)
       setRootNode(node);
   }
   //
   // Public methods
   //
   /** Sets the root. */
   public synchronized void setRootNode(Node root) {
     // save root
     this.root = root;
     // clear tree and re-populate
     DefaultMutableTreeNode where = (DefaultMutableTreeNode) getRoot();
     where.removeAllChildren();
     nodeMap.clear();
     treeNodeMap.clear();
     buildTree(root, where);
     fireTreeStructureChanged(this, new Object[] { getRoot() }, new int[0], new Object[0]);
   } // setRootNode(Node)
   /** Returns the root. */
   public Node getRootNode() {
     return root;
   }
   /** get the org.w3c.Node for a MutableTreeNode. */
   public Node getNode(Object treeNode) {
     return (Node) nodeMap.get(treeNode);
   }
   public Hashtable getAllNodes() {
     return nodeMap;
   }
   /** get the org.w3c.Node for a MutableTreeNode. */
   public TreeNode getTreeNode(Object node) {
     Object object = treeNodeMap.get(node);
     return (TreeNode) object;
   }
   //
   // Private methods
   //
   /** Builds the tree. */
   private void buildTree(Node node, MutableTreeNode where) {
     // is there anything to do?
     if (node == null) {
       return;
     }
     MutableTreeNode treeNode = insertNode(node, where);
     // iterate over children of this node
     NodeList nodes = node.getChildNodes();
     int len = (nodes != null) ? nodes.getLength() : 0;
     for (int i = 0; i < len; i++) {
       Node child = nodes.item(i);
       buildTree(child, treeNode);
     }
   } // buildTree()
   /** Inserts a node and returns a reference to the new node. */
   private MutableTreeNode insertNode(String what, MutableTreeNode where) {
     MutableTreeNode node = new DefaultMutableTreeNode(what);
     insertNodeInto(node, where, where.getChildCount());
     return node;
   } // insertNode(Node,MutableTreeNode):MutableTreeNode
   /** Inserts a text node. */
   public MutableTreeNode insertNode(Node what, MutableTreeNode where) {
     MutableTreeNode treeNode = insertNode(DOMTreeFull.toString(what), where);
     nodeMap.put(treeNode, what);
     treeNodeMap.put(what, treeNode);
     return treeNode;
   }
 } // class Model
 public static String whatArray[] = new String[] { "ALL", "ELEMENT", "ATTRIBUTE", "TEXT",
     "CDATA_SECTION", "ENTITY_REFERENCE", "ENTITY", "PROCESSING_INSTRUCTION", "COMMENT",
     "DOCUMENT", "DOCUMENT_TYPE", "DOCUMENT_FRAGMENT", "NOTATION" };
 //
 // Public methods
 //
 public static String toString(Node node) {
   StringBuffer sb = new StringBuffer();
   // is there anything to do?
   if (node == null) {
     return "";
   }
   int type = node.getNodeType();
   sb.append(whatArray[type]);
   sb.append(" : ");
   sb.append(node.getNodeName());
   String value = node.getNodeValue();
   if (value != null) {
     sb.append(" Value: \"");
     sb.append(value);
     sb.append("\"");
   }
   switch (type) {
   // document
   case Node.DOCUMENT_NODE: {
     break;
   }
   // element with attributes
   case Node.ELEMENT_NODE: {
     Attr attrs[] = sortAttributes(node.getAttributes());
     if (attrs.length > 0)
       sb.append(" ATTRS:");
     for (int i = 0; i < attrs.length; i++) {
       Attr attr = attrs[i];
       sb.append(" ");
       sb.append(attr.getNodeName());
       sb.append("=\"");
       sb.append(normalize(attr.getNodeValue()));
       sb.append(""");
     }
     sb.append(">");
     break;
   }
   // handle entity reference nodes
   case Node.ENTITY_REFERENCE_NODE: {
     break;
   }
   // cdata sections
   case Node.CDATA_SECTION_NODE: {
     break;
   }
   // text
   case Node.TEXT_NODE: {
     break;
   }
   // processing instruction
   case Node.PROCESSING_INSTRUCTION_NODE: {
     break;
   }
   // comment node
   case Node.ruMENT_NODE: {
     break;
   }
   // DOCTYPE node
   case Node.DOCUMENT_TYPE_NODE: {
     break;
   }
   // Notation node
   case Node.NOTATION_NODE: {
     sb.append("public:");
     String id = ((Notation) node).getPublicId();
     if (id == null) {
       sb.append("PUBLIC ");
       sb.append(id);
       sb.append(" ");
     }
     id = ((Notation) node).getSystemId();
     if (id == null) {
       sb.append("system: ");
       sb.append(id);
       sb.append(" ");
     }
     break;
   }
   }
   return sb.toString();
 }
 /** Normalizes the given string. */
 static protected String normalize(String s) {
   StringBuffer str = new StringBuffer();
   int len = (s != null) ? s.length() : 0;
   for (int i = 0; i < len; i++) {
     char ch = s.charAt(i);
     switch (ch) {
     case "<": {
       str.append("<");
       break;
     }
     case ">": {
       str.append(">");
       break;
     }
     case "&": {
       str.append("&");
       break;
     }
     case """: {
       str.append(""");
       break;
     }
     case "\r":
     case "\n":
     default: {
       str.append(ch);
     }
     }
   }
   return str.toString();
 } // normalize(String):String
 /** Returns a sorted list of attributes. */
 static protected Attr[] sortAttributes(NamedNodeMap attrs) {
   int len = (attrs != null) ? attrs.getLength() : 0;
   Attr array[] = new Attr[len];
   for (int i = 0; i < len; i++) {
     array[i] = (Attr) attrs.item(i);
   }
   for (int i = 0; i < len - 1; i++) {
     String name = array[i].getNodeName();
     int index = i;
     for (int j = i + 1; j < len; j++) {
       String curName = array[j].getNodeName();
       if (curName.rupareTo(name) < 0) {
         name = curName;
         index = j;
       }
     }
     if (index != i) {
       Attr temp = array[i];
       array[i] = array[index];
       array[index] = temp;
     }
   }
   return array;
 } // sortAttributes(NamedNodeMap):Attr[]

} // class DOMTreeFull


 </source>
   
  
 
  



SAX Tree Viewer

   <source lang="java">

/*--

Copyright (C) 2001 Brett McLaughlin.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions, and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions, and the disclaimer that follows 
   these conditions in the documentation and/or other materials 
   provided with the distribution.
3. The name "Java and XML" must not be used to endorse or promote products
   derived from this software without prior written permission.  For
   written permission, please contact brett@newInstance.ru.

In addition, we request (but do not require) that you include in the 
end-user documentation provided with the redistribution and/or in the 
software itself an acknowledgement equivalent to the following:
    "This product includes software developed for the
     "Java and XML" book, by Brett McLaughlin (O"Reilly & Associates)."
THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/

import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; // This is an XML book - no need for explicit Swing imports import java.awt.*; import javax.swing.*; import javax.swing.tree.*; /**

* SAXTreeViewer uses Swing to graphically
*   display an XML document.
*/

public class SAXTreeViewer extends JFrame {

   /** Default parser to use */
   private String vendorParserClass = 
       "org.apache.xerces.parsers.SAXParser";
   /** The base tree to render */
   private JTree jTree;
   /** Tree model to use */
   DefaultTreeModel defaultTreeModel;
   /**
*

This initializes the needed Swing settings.

    */
   public SAXTreeViewer() {
       // Handle Swing setup
       super("SAX Tree Viewer");
       setSize(600, 450);
   }
   /**
*

This will construct the tree using Swing.

    *
    * @param filename String path to XML document.
    */
   public void init(String xmlURI) throws IOException, SAXException {
       DefaultMutableTreeNode base = 
           new DefaultMutableTreeNode("XML Document: " + 
               xmlURI);
       
       // Build the tree model
       defaultTreeModel = new DefaultTreeModel(base);
       jTree = new JTree(defaultTreeModel);
       // Construct the tree hierarchy
       buildTree(defaultTreeModel, base, xmlURI);
       // Display the results
       getContentPane().add(new JScrollPane(jTree), 
           BorderLayout.CENTER);
   }
   /**
*

This handles building the Swing UI tree.

    *
    * @param treeModel Swing component to build upon.
    * @param base tree node to build on.
    * @param xmlURI URI to build XML document from.
    * @throws IOException - when reading the XML URI fails.
    * @throws SAXException - when errors in parsing occur.
    */
   public void buildTree(DefaultTreeModel treeModel, 
                         DefaultMutableTreeNode base, String xmlURI) 
       throws IOException, SAXException {
       // Create instances needed for parsing
       XMLReader reader = 
           XMLReaderFactory.createXMLReader(vendorParserClass);
       ContentHandler jTreeContentHandler = 
           new JTreeContentHandler(treeModel, base);
       ErrorHandler jTreeErrorHandler = new JTreeErrorHandler();
       // Register content handler
       reader.setContentHandler(jTreeContentHandler);
       // Register error handler
       reader.setErrorHandler(jTreeErrorHandler);
       // Parse
       InputSource inputSource = 
           new InputSource(xmlURI);
       reader.parse(inputSource);
   }
   /**
*

Static entry point for running the viewer.

    */
   public static void main(String[] args) {
       try {
           if (args.length != 1) {
               System.out.println(
                   "Usage: java SAXTreeViewer " +
                   "[XML Document URI]");
               System.exit(0);
           }
           SAXTreeViewer viewer = new SAXTreeViewer();
           viewer.init(args[0]);
           viewer.setVisible(true);
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

} /**

* JTreeContentHandler implements the SAX
*   ContentHandler interface and defines callback
*   behavior for the SAX callbacks associated with an XML
*   document"s content, bulding up JTree nodes.
*/

class JTreeContentHandler implements ContentHandler {

   /** Hold onto the locator for location information */
   private Locator locator;
   /** Store URI to prefix mappings */
   private Map namespaceMappings;
   /** Tree Model to add nodes to */
   private DefaultTreeModel treeModel;
   /** Current node to add sub-nodes to */
   private DefaultMutableTreeNode current;
   /**
*

Set up for working with the JTree.

    *
    * @param treeModel tree to add nodes to.
    * @param base node to start adding sub-nodes to.
    */
   public JTreeContentHandler(DefaultTreeModel treeModel, 
                              DefaultMutableTreeNode base) {
       this.treeModel = treeModel;
       this.current = base;
       this.namespaceMappings = new HashMap();
   }
   /**
*

* Provide reference to Locator which provides * information about where in a document callbacks occur. *

    *
    * @param locator Locator object tied to callback
    *        process
    */
   public void setDocumentLocator(Locator locator) {
       // Save this for later use
       this.locator = locator;
   }
   /**
*

* This indicates the start of a Document parse-this precedes * all callbacks in all SAX Handlers with the sole exception * of {@link #setDocumentLocator}. *

    *
    * @throws SAXException when things go wrong
    */
   public void startDocument() throws SAXException {
       // No visual events occur here
   }
   /**
*

* This indicates the end of a Document parse-this occurs after * all callbacks in all SAX Handlers.</code>. *

    *
    * @throws SAXException when things go wrong
    */
   public void endDocument() throws SAXException {
       // No visual events occur here
   }
   /**
*

* This indicates that a processing instruction (other than * the XML declaration) has been encountered. *

    *
    * @param target String target of PI
    * @param data String</code containing all data sent to the PI.
    *               This typically looks like one or more attribute value
    *               pairs.
    * @throws <code>SAXException when things go wrong
    */
   public void processingInstruction(String target, String data)
       throws SAXException {
       DefaultMutableTreeNode pi = 
           new DefaultMutableTreeNode("PI (target = "" + target +
                                      "", data = "" + data + "")");
       current.add(pi);
   }
   /**
*

* This indicates the beginning of an XML Namespace prefix * mapping. Although this typically occurs within the root element * of an XML document, it can occur at any point within the * document. Note that a prefix mapping on an element triggers * this callback before the callback for the actual element * itself ({@link #startElement}) occurs. *

    *
    * @param prefix String prefix used for the namespace
    *                being reported
    * @param uri String URI for the namespace
    *               being reported
    * @throws SAXException when things go wrong
    */
   public void startPrefixMapping(String prefix, String uri) {
       // No visual events occur here.
       namespaceMappings.put(uri, prefix);
   }
   /**
*

* This indicates the end of a prefix mapping, when the namespace * reported in a {@link #startPrefixMapping} callback * is no longer available. *

    *
    * @param prefix String of namespace being reported
    * @throws SAXException when things go wrong
    */
   public void endPrefixMapping(String prefix) {
       // No visual events occur here.
       for (Iterator i = namespaceMappings.keySet().iterator(); 
            i.hasNext(); ) {
           String uri = (String)i.next();
           String thisPrefix = (String)namespaceMappings.get(uri);
           if (prefix.equals(thisPrefix)) {
               namespaceMappings.remove(uri);
               break;
           }
       }
   }
   /**
*

* This reports the occurrence of an actual element. It includes * the element"s attributes, with the exception of XML vocabulary * specific attributes, such as * xmlns:[namespace prefix] and * xsi:schemaLocation. *

    *
    * @param namespaceURI String namespace URI this element
    *               is associated with, or an empty String
    * @param localName String name of element (with no
    *               namespace prefix, if one is present)
    * @param qName String XML 1.0 version of element name:
    *                [namespace prefix]:[localName]
    * @param atts Attributes list for this element
    * @throws SAXException when things go wrong
    */
   public void startElement(String namespaceURI, String localName,
                            String qName, Attributes atts)
       throws SAXException {
       DefaultMutableTreeNode element = 
           new DefaultMutableTreeNode("Element: " + localName);
       current.add(element);
       current = element;
       // Determine namespace
       if (namespaceURI.length() > 0) {
           String prefix = 
               (String)namespaceMappings.get(namespaceURI);
           if (prefix.equals("")) {
               prefix = "[None]";
           }
           DefaultMutableTreeNode namespace =
               new DefaultMutableTreeNode("Namespace: prefix = "" +
                   prefix + "", URI = "" + namespaceURI + """);
           current.add(namespace);
       }
       // Process attributes
       for (int i=0; i<atts.getLength(); i++) {
           DefaultMutableTreeNode attribute =
               new DefaultMutableTreeNode("Attribute (name = "" +
                                          atts.getLocalName(i) + 
                                          "", value = "" +
                                          atts.getValue(i) + "")");
           String attURI = atts.getURI(i);
           if (attURI.length() > 0) {
               String attPrefix = 
                   (String)namespaceMappings.get(namespaceURI);
               if (attPrefix.equals("")) {
                   attPrefix = "[None]";
               }
               DefaultMutableTreeNode attNamespace =
                   new DefaultMutableTreeNode("Namespace: prefix = "" +
                       attPrefix + "", URI = "" + attURI + """);
               attribute.add(attNamespace);            
           }
           current.add(attribute);
       }
   }
   /**
*

* Indicates the end of an element * (</[element name]>) is reached. Note that * the parser does not distinguish between empty * elements and non-empty elements, so this occurs uniformly. *

    *
    * @param namespaceURI String URI of namespace this
    *                element is associated with
    * @param localName String name of element without prefix
    * @param qName String name of element in XML 1.0 form
    * @throws SAXException when things go wrong
    */
   public void endElement(String namespaceURI, String localName,
                          String qName)
       throws SAXException {
       // Walk back up the tree
       current = (DefaultMutableTreeNode)current.getParent();
   }
   /**
*

* This reports character data (within an element). *

    *
    * @param ch char[] character array with character data
    * @param start int index in array where data starts.
    * @param length int index in array where data ends.
    * @throws SAXException when things go wrong
    */
   public void characters(char[] ch, int start, int length)
       throws SAXException {
       String s = new String(ch, start, length);
       DefaultMutableTreeNode data =
           new DefaultMutableTreeNode("Character Data: "" + s + """);
       current.add(data);
   }
   /**
*

* This reports whitespace that can be ignored in the * originating document. This is typically invoked only when * validation is ocurring in the parsing process. *

    *
    * @param ch char[] character array with character data
    * @param start int index in array where data starts.
    * @param end int index in array where data ends.
    * @throws SAXException when things go wrong
    */
   public void ignorableWhitespace(char[] ch, int start, int length)
       throws SAXException {
       
       // This is ignorable, so don"t display it
   }
   /**
*

* This reports an entity that is skipped by the parser. This * should only occur for non-validating parsers, and then is still * implementation-dependent behavior. *

    *
    * @param name String name of entity being skipped
    * @throws SAXException when things go wrong
    */
   public void skippedEntity(String name) throws SAXException {
       DefaultMutableTreeNode skipped =
           new DefaultMutableTreeNode("Skipped Entity: "" + name + """);
       current.add(skipped);
   }

} /**

* JTreeErrorHandler implements the SAX
*   ErrorHandler interface and defines callback
*   behavior for the SAX callbacks associated with an XML
*   document"s warnings and errors.
*/

class JTreeErrorHandler implements ErrorHandler {

   /**
*

* This will report a warning that has occurred; this indicates * that while no XML rules were "broken", something appears * to be incorrect or missing. *

    *
    * @param exception SAXParseException that occurred.
    * @throws SAXException when things go wrong 
    */
   public void warning(SAXParseException exception)
       throws SAXException {
           
       System.out.println("**Parsing Warning**\n" +
                          "  Line:    " + 
                             exception.getLineNumber() + "\n" +
                          "  URI:     " + 
                             exception.getSystemId() + "\n" +
                          "  Message: " + 
                             exception.getMessage());        
       throw new SAXException("Warning encountered");
   }
   /**
*

* This will report an error that has occurred; this indicates * that a rule was broken, typically in validation, but that * parsing can reasonably continue. *

    *
    * @param exception SAXParseException that occurred.
    * @throws SAXException when things go wrong 
    */
   public void error(SAXParseException exception)
       throws SAXException {
       
       System.out.println("**Parsing Error**\n" +
                          "  Line:    " + 
                             exception.getLineNumber() + "\n" +
                          "  URI:     " + 
                             exception.getSystemId() + "\n" +
                          "  Message: " + 
                             exception.getMessage());
       throw new SAXException("Error encountered");
   }
   /**
*

* This will report a fatal error that has occurred; this indicates * that a rule has been broken that makes continued parsing either * impossible or an almost certain waste of time. *

    *
    * @param exception SAXParseException that occurred.
    * @throws SAXException when things go wrong 
    */
   public void fatalError(SAXParseException exception)
       throws SAXException {
   
       System.out.println("**Parsing Fatal Error**\n" +
                          "  Line:    " + 
                             exception.getLineNumber() + "\n" +
                          "  URI:     " + 
                             exception.getSystemId() + "\n" +
                          "  Message: " + 
                             exception.getMessage());        
       throw new SAXException("Fatal Error encountered");
   }

} // Demo file: book.xml /* <?xml version="1.0"?> <games>

 <game genre="rpg">XML Invaders</game>
 <game genre="rpg">A Node in the XPath</game>
 <game genre="rpg">XPath Racers</game>

</games>

  • /


 </source>
   
  
 
  



XML Tree: Simple XML utility class

   <source lang="java">

import java.awt.Color; import java.awt.ruponent; import java.io.File; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.ToolTipManager; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class VSX2 {

 public TreeModel parse(String filename) throws Exception {
   SAXParserFactory factory = SAXParserFactory.newInstance();
   XMLIconTreeHandler handler = new XMLIconTreeHandler();
   SAXParser saxParser = factory.newSAXParser();
   saxParser.parse(new File(filename), handler);
   return new DefaultTreeModel(handler.getRoot());
 }
 public static class XMLIconTreeHandler extends DefaultHandler {
   private DefaultMutableTreeNode root, currentNode;
   public DefaultMutableTreeNode getRoot() {
     return root;
   }
   public void startElement(String namespaceURI, String lName, String qName, Attributes attrs)
       throws SAXException {
     String eName = lName;
     if ("".equals(eName))
       eName = qName;
     ITag t = new ITag(eName, attrs);
     DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(t);
     if (currentNode == null) {
       root = newNode;
     } else {
       currentNode.add(newNode);
     }
     currentNode = newNode;
   }
   public void endElement(String namespaceURI, String sName, String qName) throws SAXException {
     currentNode = (DefaultMutableTreeNode) currentNode.getParent();
   }
   public void characters(char buf[], int offset, int len) throws SAXException {
     String s = new String(buf, offset, len).trim();
     ((ITag) currentNode.getUserObject()).addData(s);
   }
 }
 public static class ITag implements IconAndTipCarrier {
   private String name;
   private String data;
   private Attributes attr;
   private Icon icon;
   private String tipText;
   public ITag(String n, Attributes a) {
     name = n;
     attr = a;
     for (int i = 0; i < attr.getLength(); i++) {
       String aname = attr.getQName(i);
       String value = attr.getValue(i);
       if (aname.equals("icon")) {
         tipText = value;
         icon = new ImageIcon(value);
         break;
       }
     }
   }
   public String getName() {
     return name;
   }
   public Attributes getAttributes() {
     return attr;
   }
   public void setData(String d) {
     data = d;
   }
   public String getData() {
     return data;
   }
   public String getToolTipText() {
     return tipText;
   }
   public Icon getIcon() {
     return icon;
   }
   public void addData(String d) {
     if (data == null) {
       setData(d);
     } else {
       data += d;
     }
   }
   public String getAttributesAsString() {
     StringBuffer buf = new StringBuffer(256);
     for (int i = 0; i < attr.getLength(); i++) {
       buf.append(attr.getQName(i));
       buf.append("=\"");
       buf.append(attr.getValue(i));
       buf.append("\"");
     }
     return buf.toString();
   }
   public String toString() {
     String a = getAttributesAsString();
     return name + ": " + a + (data == null ? "" : " (" + data + ")");
   }
 }
 public static void main(String args[]) throws Exception {
   JFrame frame = new JFrame("Tree Renderer Test");
   VSX2 parser = new VSX2();
   JTree tree = new JTree(parser.parse("testfile.xml"));
   // Steal the default icons from the default renderer...
   DefaultTreeCellRenderer rend1 = new DefaultTreeCellRenderer();
   IconAndTipRenderer rend2 = new IconAndTipRenderer(rend1.getOpenIcon(), rend1.getClosedIcon(),
       rend1.getLeafIcon());
   tree.setCellRenderer(rend2);
   ToolTipManager.sharedInstance().registerComponent(tree);
   frame.getContentPane().add(new JScrollPane(tree));
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(300, 400);
   frame.setVisible(true);
 }

} interface IconAndTipCarrier {

 public Icon getIcon();
 public String getToolTipText();

} class IconAndTipRenderer extends JLabel implements TreeCellRenderer {

 Color backColor = new Color(0xFF, 0xCC, 0xFF);
 Icon openIcon, closedIcon, leafIcon;
 String tipText = "";
 public IconAndTipRenderer(Icon open, Icon closed, Icon leaf) {
   openIcon = open;
   closedIcon = closed;
   leafIcon = leaf;
   setBackground(backColor);
   setForeground(Color.black);
 }
 public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
     boolean expanded, boolean leaf, int row, boolean hasFocus) {
   setText(value.toString());
   if (selected) {
     setOpaque(true);
   } else {
     setOpaque(false);
   }
   IconAndTipCarrier itc = null;
   if (value instanceof DefaultMutableTreeNode) {
     Object uo = ((DefaultMutableTreeNode) value).getUserObject();
     if (uo instanceof IconAndTipCarrier) {
       itc = (IconAndTipCarrier) uo;
     }
   } else if (value instanceof IconAndTipCarrier) {
     itc = (IconAndTipCarrier) value;
   }
   if ((itc != null) && (itc.getIcon() != null)) {
     setIcon(itc.getIcon());
     tipText = itc.getToolTipText();
   } else {
     tipText = " ";
     if (expanded) {
       setIcon(openIcon);
     } else if (leaf) {
       setIcon(leafIcon);
     } else {
       setIcon(closedIcon);
     }
   }
   return this;
 }
 public String getToolTipText() {
   return tipText;
 }

}


 </source>
   
  
 
  



XML Tree View

   <source lang="java">

/*

 Java, XML, and Web Services Bible
 Mike Jasnowski
 ISBN: 0-7645-4847-6
  • /

import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.Event.*; import java.io.*; import javax.swing.tree.*; import org.xml.sax.*; import org.xml.sax.helpers.*; import org.apache.xerces.parsers.*; public class XMLTreeView {

      private SAXTreeBuilder saxTree = null;
      private static String file = "";
      
      public static void main(String args[]){
             JFrame frame = new JFrame("XMLTreeView: [ games.xml ]");
             frame.setSize(400,400);
             
             frame.addWindowListener(new WindowAdapter(){
                  public void windowClosing(WindowEvent ev){
                      System.exit(0);
                  }
             });
             file = "games.xml";
             new XMLTreeView(frame);
      }
      
      public XMLTreeView(JFrame frame){ 
             frame.getContentPane().setLayout(new BorderLayout());  
             DefaultMutableTreeNode top = new DefaultMutableTreeNode(file);

// DefaultMutableTreeNode top = new DefaultMutableTreeNode("XML Document");

             saxTree = new SAXTreeBuilder(top); 
             
             try {             
             SAXParser saxParser = new SAXParser();
             saxParser.setContentHandler(saxTree);
             saxParser.parse(new InputSource(new FileInputStream(file)));
             }catch(Exception ex){
                top.add(new DefaultMutableTreeNode(ex.getMessage()));
             }
             JTree tree = new JTree(saxTree.getTree()); 
             JScrollPane scrollPane = new JScrollPane(tree);
             
             frame.getContentPane().add("Center",scrollPane);                                           
             frame.setVisible(true);       
             
       } 
       
    

} class SAXTreeBuilder extends DefaultHandler{

      private DefaultMutableTreeNode currentNode = null;
      private DefaultMutableTreeNode previousNode = null;
      private DefaultMutableTreeNode rootNode = null;
      public SAXTreeBuilder(DefaultMutableTreeNode root){
             rootNode = root;
      }
      public void startDocument(){
             currentNode = rootNode;
      }
      public void endDocument(){
      }
      public void characters(char[] data,int start,int end){
             String str = new String(data,start,end);              
             if (!str.equals("") && Character.isLetter(str.charAt(0)))
                 currentNode.add(new DefaultMutableTreeNode(str));           
      }
      public void startElement(String uri,String qName,String lName,Attributes atts){
             previousNode = currentNode;
             currentNode = new DefaultMutableTreeNode(lName);
             // Add attributes as child nodes //
             attachAttributeList(currentNode,atts);
             previousNode.add(currentNode);              
      }
      public void endElement(String uri,String qName,String lName){
             if (currentNode.getUserObject().equals(lName))
                 currentNode = (DefaultMutableTreeNode)currentNode.getParent();              
      }
      public DefaultMutableTreeNode getTree(){
             return rootNode;
      }
      
      private void attachAttributeList(DefaultMutableTreeNode node,Attributes atts){
              for (int i=0;i<atts.getLength();i++){
                   String name = atts.getLocalName(i);
                   String value = atts.getValue(name);
                   node.add(new DefaultMutableTreeNode(name + " = " + value));
              }
      }
      

} //games.xml /* <?xml version="1.0"?> <games>

 <game genre="rpg">XML Invaders</game>
 <game genre="rpg">A Node in the XPath</game>
 <game genre="rpg">XPath Racers</game>

</games>

  • /


 </source>