Visiting All the Nodes in a DOM Document - Java XML

Java examples for XML:DOM

Description

Visiting All the Nodes in a DOM Document

Demo Code


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

public class Main {
  public static void main(String[] argv) {
    // Obtain an DOM document; this method is implemented in
    Document doc = null;/*from w  ww.  j a v a  2 s  .  c o m*/

    visit(doc, 0);

  }// This method visits all the nodes in a DOM tree

  public static void visit(Node node, int level) {
    // Process node

    // If there are any children, visit each one
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
      // Get child node
      Node childNode = list.item(i);

      // Visit child node
      visit(childNode, level + 1);
    }
  }
}

Related Tutorials