Java HTML / XML How to - Visit All the Nodes in a DOM Document








Question

We would like to know how to visit All the Nodes in a DOM Document.

Answer

     /*from   w  ww  . j a v a2 s  .  c  o m*/
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {
  public static String getXMLData() {
    return "<x></x>";
  }

  public static void main(String[] argv) throws Exception{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  

    Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(getXMLData())));

    visit(doc, 0);
  }
  public static void visit(Node node, int level) {
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
      Node childNode = list.item(i);
      System.out.println(childNode);
      visit(childNode, level + 1);
    }
  }
}

The code above generates the following result.