- Alternative API: SAX
- SAX: The Power API
- Commonly Used SAX Interfaces and Classes
- Maintaining the State
- Flexibility
Commonly Used SAX Interfaces and Classes
We have looked at only one event (startElement()) so far. Before going any further, let's review the main interfaces defined by SAX.
NOTE
There have been two versions of SAX so far: SAX1 and SAX2. This chapter introduces the SAX2 API only.
SAX1 is very similar to SAX2 but it lacks namespace handling.
NOTE
This section is not a comprehensive reference to SAX. Instead it concentrates on the most frequently used classes.
Main SAX Events
SAX groups its events in a few interfaces:
ContentHandler defines events related to the document itself (such as opening and closing tags). Most applications register for these events.
DTDHandler defines events related to the DTD. However, it does not define enough events to completely report on the DTD. If you need to parse a DTD, use the optional DeclHandler. DeclHandler is an extension to SAX and it is not supported by all parsers.
EntityResolver defines events related to loading entities. Few applications register for these events.
ErrorHandler defines error events. Many applications register for these events to report errors in their own way.
To simplify work, SAX provides a default implementation for these interfaces in the DefaultHandler class. In most cases, it is easier to extend DefaultHandler and override the methods that are relevant for the application rather than to implement an interface directly.
XMLReader
To register event handlers and to start parsing, the application uses the XMLReader interface. As we have seen, parse(), a method of XMLReader, starts the parsing:
parser.parse(args[0]);
XMLReader's main methods are
parse() parses an XML document. There are two versions of parse(): One accepts a filename or an URL, the other an InputSource object (see the section "InputSource").
setContentHandler(), setDTDHandler(), setEntityResolver(), and setErrorHandler() let the application register event handlers.
setFeature() and setProperty() control how the parser work. They take a property or feature identifier, which is an URIsimilar to namespacesand a value. Features take Boolean values whereas properties take Objects.
The most commonly used features are
http://xml.org/sax/features/namespaces which all SAX parsers recognize. When set to true (the default), the parser recognizes namespaces and resolves prefix when calling ContentHandler's methods.
http://xml.org/sax/features/validation which is optional. If it is set to true, a validating parser validates the document. Nonvalidating parsers ignore this feature.
XMLReaderFactory
XMLReaderFactory creates the parser object. It defines two versions of createXMLReader(): One takes the class name for the parser as a parameter; the second obtains the class name from the org.xml.sax.driver system property.
For Xerces, the class is org.apache.xerces.parsers.SAXParser. You should use XMLReaderFactory because it makes it easy to switch to another SAX parser. Indeed, it requires changing only one line and recompiling:
XMLReader parser = XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser");
For more flexibility, the application can read the class name from the command line or use the parameterless createXMLReader(). It is, therefore, possible to change the parser without even recompiling.
InputSource
InputSource controls how the parser reads files, including XML documents and entities.
In most cases, documents are loaded from an URL. However, applications with special needs can override InputSource. This is used, for example, to load documents from databases.
ContentHandler
ContentHandler is the most commonly used SAX interface because it defines events for the XML document.
As we have seen, Listing 8.2 implements startElement(), an event defined in ContentHandler. It registers the ContentHandler with the parser:
Cheapest cheapest = new Cheapest(); // ... parser.setContentHandler(cheapest);
ContentHandler declares the following events:
startDocument()/endDocument() notifies the application of the document's beginning or ending.
startElement()/endElement() notifies the application of an opening or closing tag. Attributes are passed as an Attributes parameter; see the following section on "Attributes." Empty elements (for example, <img href="logo.gif"/>) generate both startElement() and endElement(),even though there is only one tag.
startPrefixMapping()/endPrefixMapping() notifies the application of a namespace scope. You seldom need this information because the parser already resolves namespaces when the http://xml.org/sax/features/namespaces is true.
characters()/ignorableWhitespace() notifies the application when the parser finds text (parsed character data) in an element. Beware, the parser is entitled to spread the text across several events (to better manage its buffer). The ignorableWhitespace event is used for ignorable spaces as defined by the XML standard.
processingInstruction() notifies the application of processing instructions.
skippedEntity() notifies the application that an entity has been skipped (that is, when a parser has not seen the entity declaration in the DTD/schema).
setDocumentLocator()passes a Locator object to the application; see the section Locator that follows. Note that the SAX parser is not required to supply a Locator, but if it does, it must fire this event before any other event.
Attributes
In the startElement() event, the application receives the list of attributes in an Attributes parameter:
String attribute = attributes.getValue("","price");Attributes defines the following methods:
getValue(i)/getValue(qName)/getValue(uri,localName) returns the value of the ith attribute or the value of an attribute whose name is given.
getLength() returns the number of attributes.
getQName(i)/getLocalName(i)/getURI(i) returns the qualified name (with the prefix), local name (without the prefix), and namespace URI of the ith attribute.
getType(i)/getType(qName)/getType(uri,localName) returns the type of the ith attribute or the type of the attribute whose name is given. The type is a string, as used in the DTD: "CDATA", "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", or "NOTATION".
CAUTION
The Attributes parameter is available only during the startElement() event. If you need it between events, make a copy with AttributesImpl.
Locator
A Locator provides line and column positions to the application. The parser is not required to provide a Locator object.
Locator defines the following methods:
getColumnNumber() returns the column where the current event ends. In an endElement() event, it would return the last column of the end tag.
getLineNumber() returns the line in which the current event ends. In an endElement() event, it would return the line of the end tag.
getPublicId() returns the public identifier for the current document event.
getSystemId() returns the system identifier for the current document event.
DTDHandler
DTDHandler declares two events related to parsing the DTD:
notationDecl() notifies the application that a notation has been declared.
unparsedEntityDecl() notifies the application that an unparsed entity declaration has been found.
EntityResolver
The EntityResolver interface defines only one event, resolveEntity(), which returns an InputSource.
» The InputSource is introduced in the section "InputSource" on page 267.
Because the SAX parser can resolve most URLs already, few applications implement EntityResolver. The exception is catalog files. If you need catalog files in your application, download Norman Walsh's catalog package from http://www.arbortext.com/Customer_Support/Updates_and_Technical_Notes/java_form.html.
» Catalog files resolve public identifiers to system identifiers. They were introduced in the section "The DTD Syntax" in Chapter 4 on page 91.
ErrorHandler
The ErrorHandler interface defines events for errors. Applications that handle these events can provide custom error processing.
After a custom error handler is installed, the parser doesn't throw exceptions anymore. Throwing exceptions is the responsibility of the event handlers.
The interface defines three methods that correspond to three levels or gravity of errors:
warning() signals problems that are not errors as defined by the XML specification. For example, some parsers issue a warning when there is no XML declaration. It is not an error (because the declaration is optional), but it might be worth noting.
error() signals errors as defined by the XML specification.
fatalError() signals fatal errors, as defined by the XML specification.
SAXException
Most methods defined by the SAX standard can throw SAXException. A SAXException signals an error while parsing the XML document.
The error can either be a parsing error or an error in an event handler. To report other exceptions from the event handler, it is possible to wrap exceptions in SAXException.
Suppose an event handler catches an IndexOutOfBoundsException while processing the startElement event. The event handler can wrap the IndexOutOfBoundsException in a SAXException:
public void startElement(String uri, String name, String qualifiedName, Attributes attributes) { try { // the code may throw an IndexOutOfBoundsException } catch(IndexOutOfBounds e) { throw new SAXException(e); } }
The SAXException flows all the way up to the parse() method where it is caught and interpreted:
try { parser.parse(uri); } catch(SAXException e) { Exception x = e.getException(); if(null != x) if(x instanceof IndexOutOfBoundsException) // process the IndexOutOfBoundsException }