SAX Readers

Without spending any further time on the preliminaries, it’s time to code. As a sample to familiarize you with SAX, this chapter details the SAXTreeViewer class. This class uses SAX to parse an XML document supplied on the command line, and displays the document visually as a Swing JTree. If you don’t know anything about Swing, don’t worry; I don’t focus on that, but just use it for visual purposes. The focus will remain on SAX, and how events within parsing can be used to perform customized action. All that really happens is that a JTree is used, which provides a nice simple tree model, to display the XML input document. The key to this tree is the DefaultMutableTreeNode class, which you’ll get quite used to in using this example, as well as the DefaultTreeModel that takes care of the layout.

The first thing you need to do in any SAX-based application is get an instance of a class that conforms to the SAX org.xml.sax.XMLReader interface. This interface defines parsing behavior and allows us to set features and properties (which I’ll cover later in this chapter). For those of you familiar with SAX 1.0, this interface replaces the org.xml.sax.Parser interface.

Warning

This is a good time to point out that SAX 1.0 is not covered in this book. While there is a very small section at the end of this chapter explaining how to convert SAX 1.0 code to SAX 2.0, you really are not in a good situation if you are using SAX 1.0. While the first edition of this book came ...

Get Java and XML, Second Edition 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.