Print DOM recursively in Java

Description

The following code shows how to print DOM recursively.

Example


/* ww w .  j a v a2  s .c o  m*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {

  public static void main(String[] argv) throws Exception{

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.newDocument();

      Element root = doc.createElementNS(null, "Site"); 
      Element item = doc.createElementNS(null, "name"); 
      item.appendChild(doc.createTextNode("java2s.com"));
      root.appendChild(item); 
      item = doc.createElementNS(null, "topic"); 
      item.appendChild(doc.createTextNode("java"));
      root.appendChild(item);
      item = doc.createElementNS(null, "topic");
      item.appendChild(doc.createTextNode("xml"));
      root.appendChild(item);
      doc.appendChild(root);
  
      printTree(doc);
  }
  
  public static void printTree(Node doc) {
    if (doc == null) {
      System.out.println("Nothing to print!!");
      return;
    }
      System.out.println(doc.getNodeName() + "  " + doc.getNodeValue());
      NamedNodeMap cl = doc.getAttributes();
      if(cl != null){
        for (int i = 0; i < cl.getLength(); i++) {
          Node node = cl.item(i);
          System.out.println(
            "\t" + node.getNodeName() + " ->" + node.getNodeValue());
        }
        
      }
      NodeList nl = doc.getChildNodes();
      for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        printTree(node);
      }
  
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    XML »




DOM
SAX