Parsing XML with SAX: creating a DefaultHandler

In our SAX introduction, we mentioned that we need to override the DefaultHandler class. This class contains (overridable) methods that will be called when various events occur during parsing, principally when parsing reaches start and end tags, and when it has pulled out the text or contents of a tag.

A typical skeleton handler would look as follows:

public class MyHandler extends DefaultHandler {
  public void startElement (String uri, String localName,
  			          String qName, Attributes attributes)
                              throws SAXException {
    ...
  }
  public void endElement (String uri, String localName,
  			        String qName, Attributes attributes)
                              throws SAXException {
    ...
  }
  public void characters (char ch[], int start, int length)
	throws SAXException {
    ...
  }
}

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.