A simple XML parser that builds a tree from SAX events : XML Tree « XML « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » XML » XML Tree 




A simple XML parser that builds a tree from SAX events
A simple XML parser that builds a tree from SAX events
  
/*
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 attrsthrows 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 = (DefaultMutableTreeNodecurrentNode.getParent();
    }

    public void characters(char buf[]int offset, int len)
        throws SAXException {
      String s = new String(buf, offset, len).trim();
      ((TagcurrentNode.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(300400);
    frame.setVisible(true);
  }
}

           
         
    
  














Related examples in the same category
1.XML Tree: Simple XML utility class
2.DOM Tree Walker Tree Model
3.Demo Tree WalkerDemo Tree Walker
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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.