Java HTML / XML How to - Create Recursive XML-parser








Question

We would like to know how to create Recursive XML-parser.

Answer

import java.util.ArrayList;
import java.util.List;
/*from   w w  w  .  j a  va  2 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.Node;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(final String[] args) throws Exception {
    new Main("file.xml");
  }
  public Main(final String file) throws Exception {
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document doc = docBuilder.parse(this.getClass().getResourceAsStream(
        file));
    List<String> l = new ArrayList<String>();
    parse(doc, l, doc.getDocumentElement());
    System.out.println(l);
  }

  private void parse(final Document doc, final List<String> list,
      Element e) {
    NodeList children = e.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
      Node n = children.item(i);
      if (n.getNodeType() == Node.ELEMENT_NODE) {
        list.add(n.getNodeName());
        parse(doc, list, (Element) n);
      }
    }
  }
}