Java HTML / XML How to - Get a node from xml without knowing its level








Question

We would like to know how to get a node from xml without knowing its level.

Answer

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
//from  ww w  . jav  a 2  s.c o  m
class MyHandler extends DefaultHandler {
  @Override
  public void startElement(String uri, String localName, String qName,
      Attributes attributes) throws SAXException {
    if (qName.equals("child2")) {
      // here you go do what you need here with the attributes
    }
  }
}

public class Main {

  public static void main(String[] args) throws Exception {
    XMLReader parser = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
    ContentHandler contentHandler = new MyHandler();
    parser.setContentHandler(contentHandler);

    parser.parse("foo.xml");
  }
}