The Java Program: DOMEcho.java

  1 import javax.xml.parsers.*;  // j2se 1.4
  2 import org.w3c.dom.*;
  3 import java.io.*;
  4 
  5 public class DOMEcho {
  6 
  7    public static void main (String[] args) throws Exception {
  8       final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  9       try {
 10          final DocumentBuilder db = dbf.newDocumentBuilder();
 11          final Document doc = db.parse (new File (args[0]));
 12          echo (doc);
 13       } catch (IOException e) {
 14          System.err.println (e);
 15       }
 16    }
 17 
 18    static void echo (Node n) {
 19       final int type = n.getNodeType();
 20       switch (type) {
 21       case Node.DOCUMENT_NODE: System.out.println ("DOC:"); break;
 22       case Node.DOCUMENT_TYPE_NODE: System.out.println ("DOC_TYPE:"); break;
 23       case Node.ELEMENT_NODE: System.out.println ("ELEM:"); break;
 24       case Node.TEXT_NODE: System.out.println ("TEXT:"); break;
 25       default:  System.out.print ("other node:  " + type);
 26          break;
 27       }
 28       System.out.print (" nodeName=\"" + n.getNodeName() + "\"");
 29       final String val = n.getNodeValue();
 30       if (val != null && !(val.trim().equals(""))) {
 31          System.out.println (" nodeValue \"" + n.getNodeValue() +"\"");
 32       }
 33       System.out.println ();
 34 
 35       for (Node child = n.getFirstChild(); child !=null; child=child.getNextSibling()) {
 36          echo (child);
 37       }
 38    }
 39 }