DOMTest2.java



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

/** print all name of DOM Nodes */
public class DOMTest2 {

  /** DocumentBuilderFactory */
    private DocumentBuilderFactory dbf;

  /** DocumentBuilder */
    private DocumentBuilder db;

  /** constructor */
    public DOMTest2() {
        try {
            dbf = DocumentBuilderFactory.newInstance();
                // System.out.println( dbf.toString() );
            db = dbf.newDocumentBuilder();
                // System.out.println( db.toString() );
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
    }

  /** print Node name recursively */
    public void printNode( Node node, int depth ) {

        printIndents( depth );
        if( node.getNodeType() == Node.ELEMENT_NODE ) {
            System.out.print( node.getNodeName() + ":" );
            NamedNodeMap nnp = node.getAttributes();
            printAttrs( nnp );
        }
        else if( node.getNodeType() == Node.TEXT_NODE ) {
            System.out.print( "\"" + ((Text)node).getData() + "\"" );
        }
        else {
            System.out.println( node.getNodeName() );
        }

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

            printNode( list.item(i), depth+1 );
        }
    }

  /** print Attributes info */
    private void printAttrs( NamedNodeMap nnp ) {

        for( int i=0; i<nnp.getLength(); i++ ) {

            Node n = nnp.item( i );
            if( n.getNodeType() == Node.ATTRIBUTE_NODE ) {
                Attr a = (Attr)n;
                System.out.print( "[" + a.getName()
                                + "=" + a.getValue() + "]" );
            }
        }
        System.out.println( "" );
    }

  /** to show tree structure */
    public void printIndents( int depth ) {
        for( int i=0; i<depth; i++ )
            System.out.print( "  " );
    }

  /** start here */
    public static void main( String[] argv ) {
        try {
            DOMTest2 test = new DOMTest2();
            InputSource source = new InputSource( argv[0] );
            Document doc = test.db.parse( source );
            test.printNode( doc, 0 );
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
    }
}