Today's tip continues our discussion on parsing XML using Java and the
SAX API. In our previous tip, I showed you some boilerplate code for creating
a SAX parser and parsing a document. The interesting part of using SAX,
however, is implementing the document handler. Recall that SAX is an event-based
API. This means, basically, you give it an instance of a class and it calls
methods of the class to handle the various items in the XML document. To
implement this, the SAX API defines an interface named DocumentHandler.
Here is a sample, skeleton document handler (for simplicity, it shows only
a few of the more commonly used methods):
class MyDocumentHandler implements DocumentHandler { public void startDocument () throws SAXException { // called once, at the start of the document } public void endDocument () throws SAXException { // called once, at the end of the document } public void startElement (String name, AttributeList attrs) throws SAXException { // called when an element is encountered } public void endElement (String name) throws SAXException { // called at the end of an element } public void characters (char buf [], int offset, int len) throws SAXException { // provides the content of elements } }