DOMTree.java



import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;

import javax.swing.*;
import javax.swing.tree.*;

/** show DOM Nodes as a swing JTree class */
public class DOMTree {

  /** the Tree object */
    public JTree tree;

  /** root Node of the Tree object */
    private DefaultMutableTreeNode root;

  /** DocumentBuilderFactory */
    private DocumentBuilderFactory dbf;

  /** DocumentBuilder */
    private DocumentBuilder db;

  /** constructor */
    public DOMTree( InputSource source ) {
        try {
            dbf = DocumentBuilderFactory.newInstance();
            db = dbf.newDocumentBuilder();
            Document doc = db.parse( source );
            Node rootTag = doc.getFirstChild();
            if( rootTag == null
               || rootTag.getNodeType() != Node.ELEMENT_NODE ) {
                System.err.println( "Not Valid Source" );
                System.exit(-1);
            }

            root = new DefaultMutableTreeNode(
                                         rootTag.getNodeName() );
            tree = new JTree( root );
            addChildren( rootTag, root );
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
    }

  /** add Children Element Nodes to the Tree object */
    public void addChildren( Node node,
                          DefaultMutableTreeNode branch ) {

        NodeList list = node.getChildNodes();
        if( list.getLength() == 0 )
            return;
        for( int i=0; i<list.getLength(); i++ ) {

            Node child = list.item( i );
            if( child.getNodeType() != Node.ELEMENT_NODE ) {
                continue;
            }
            DefaultMutableTreeNode tn
               = new DefaultMutableTreeNode( child.getNodeName() );
            branch.add( tn );
            addChildren( child, tn );
        }
    }

  /** start here */
    public static void main( String[] argv ) {
        try {
            InputSource source = new InputSource( argv[0] );
            DOMTree domtree = new DOMTree( source );
            JFrame frame = new JFrame( "DOM Tree" );
            frame.getContentPane().add( domtree.tree, "Center" );
            frame.setSize( 200, 500 );
            frame.show();
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
    }
}