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








Question

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

Answer

import java.io.StringReader;
/* w  ww .  j a  v  a 2s.com*/
import javax.xml.parsers.DocumentBuilderFactory;

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

public class Main {
  public static String getXMLData(){
    return "<a><img/><x></x></a>";
  }
  
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(getXMLData())));
    NodeList list = doc.getElementsByTagName("*");
    for (int i = 0; i < list.getLength(); i++) {
      Element element = (Element) list.item(i);
      System.out.println(element);
    }
  }
}

The code above generates the following result.