Basic ContentHandler Events

You’ve just seen how the parts of a SAX2 application fit together, so now you’re ready to see how the data is actually handled as it arrives. Here we focus on the events that deal with the core XML data model of elements, attributes, and text. To work with that model, you need to use only a handful of methods from the ContentHandler interface.

The DefaultHandler Class

As mentioned earlier, this class is a convenient way to start using SAX2 because it provides stubs for many of the handler methods. You can just override those stubs with methods to do real work. Using DefaultHandler as a base class is just an implementation option. It’s often just as convenient not to use such a base class. The class is used in this chapter to avoid explaining handler methods that you don’t really need.

In some scenarios, Sun’s JAXP requires you to use DefaultHandler as a base class. That’s much more of a restriction than SAX itself makes. If you stick to using the SAX XMLReader API, as recommended in this book, you’ll still have the option of using DefaultHandler as a base class, but this policy won’t be imposed on your application code. For example, you can have separate objects to encapsulate policies such as error handling, so you won’t need to hardwire all such policies into a single class.

Example: Elements and Text

Let’s use this simple XML document to learn the most essential SAX callbacks:

<stanza> <line>In a cavern, in a canyon,</line> <line>Excavating for ...

Get SAX2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.