JDK (Java Development Kit) Tutorials
Dr. Herong Yang, Version 5.00

SAX Content Handler Interface

This section describes the SAX content handler interface, org.xml.sax.ContentHandler, which allows you write your own SAX handler by implementing its event handler methods like startElement() and endElement().

As I mentioned earlier, while the SAX parser is parsing an XML file, it fires events. The first group of such events are designed into an interface, org.xml.sax.ContentHandler. It contains the following XML content related events:

  • startDocument(): When parsing reaches the beginning of the XML document.
  • endDocument(): When parsing reaches the end of the XML document.
  • startElement(): When parsing reaches the beginning of an XML element.
  • endElement(): When parsing reaches the end of an XML element.
  • characters(): When parsing reaches the end of an character section.
  • ignorableWhitespace(): When parsing reaches any ignorable white spaces between elements.

Of course, some of these events also pass information parsed from the XML file to the event handler as parameters. For example:

  • startElement() passes all the attributes as an org.xml.sax.Attributes object.
  • characters() passes all the characters of the parsed text as char[] object.

JDK also provides a default SAX handler org.xml.sax.helpers.DefaultHandler, that implements the org.xml.sax.ContentHandler.

To write your own SAX handler class, you can simple extends the org.xml.sax.helpers.DefaultHandler, and override any specific event handler methods that you are interested. See the next section for a sample program.

Last update: 2006.

Sections in This Chapter

SAX (Simple API for XML) Implementation in JDK

SAX Content Handler Interface

SAXBrowser.java - SAX Based XML Browser

Dr. Herong Yang, updated in 2008
SAX Content Handler Interface