Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

The Glue of SAX: XMLReader

SAX defines the XMLReader interface to tie together many of the interfaces discussed so far. This interface is typically implemented by XML parsers but can be implemented by anyone who needs to tie together implementations of the various handler interfaces whose stream of method invocations represent an XML document information item. The XMLReader interface has three families of methods: handler methods, configuration methods, and parse methods. The handler methods consist of four get/set method pairs that allow implementations of ContentHandler, DTDHandler, ErrorHandler, and EntityResolver to be tied together to interpret a single document information item.

package org.xml.sax;
public interface XMLReader {
  void           setContentHandler(ContentHandler handler);
  ContentHandler getContentHandler();
  void           setDTDHandler(DTDHandler handler);
  DTDHandler     getDTDHandler();
  void           setEntityResolver(EntityResolver resolver);
  EntityResolver getEntityResolver();
  void           setErrorHandler(ErrorHandler handler);
  ErrorHandler   getErrorHandler();
       :               :

Note that there are no XMLReader methods that correspond to DeclHandler or LexicalHandler. Rather, these two interfaces are dealt with by the second group of methods that focus on configuration.

XMLReader has four configuration methods: two that deal with properties and two that deal with features. Properties are uniquely named values that canbe associated with an XMLReader instance. Features can be viewed as configuration-specific boolean properties that are used to turn specific processing features on or off.

SAX2 predefines a set of well-known properties and features, which are listed in Tables 2.1 and 2.2 . To support extensibility, properties and features are

Table 2.1. SAX2 Features

Feature True
namespaces Perform namespace processing.
namespace-prefixes Report the original prefixed names and attributes used for Namespace declarations.
string-interning All element names, prefixes, attribute names, Namespace URIs, and local names are internal ized using java.lang.String.intern.
external-general-entities Include external general (text) entities.
external-parameter-entities Include external parameter entities and the external DTD subset.
validation Report all validation errors (implies external- general-entities and external-parameter-entities).
Note: Feature IDs prefixed with http://xml.org/sax/features/.

Table 2.2. SAX2 Properties

Property Description [Type]
dom-node The DOM node currently being visited, if SAX is being used as a DOM iterator. If the parser recognizes and supports this property but is not currently visiting a DOM node, return null. [DOM Node—Read Only]
Xml-string Get the string of characters associated with the current event. If the parser recognizes and supports this property but is not currently parsing text, it should return null. [String—Read Only]
lexical-handler An optional extension handler for lexical events like comments.
declaration-handler An optional extension handler for DTD-related events other than notations and unparsed entities.
Note: Property IDs prefixed with http://xml.org/sax/properties/.

named by URIs. If the XMLReader implementation recognizes the property/feature name but does not support it, it must throw a SAXNotSupported Exception. If the XMLReader implementation does not recognize the property/feature name to begin with, it must throw a SAXNotRecognizedException. The four configuration methods are defined as follows:

package org.xml.sax;
public interface XMLReader {
       :               :
  object getProperty (String name)
            throws SAXNotRecognizedException,
                    SAXNotSupportedException;
  void   setProperty (String name, Object value)
               throws  SAXNotRecognizedException,
                       SAXNotSupportedException;
  boolean getFeature (String name)
             throws  SAXNotRecognizedException,
                      SAXNotSupportedException;
  void    setFeature (String name, Boolean value)
                throws  SAXNotRecognizedException,
                        SAXNotSupportedException;
       :                :
}

The concrete type of a property value is property-specific. Because features are used to turn processing features on or off, the type of a feature is hardwired to boolean.

Note that two of the predefined properties are the DeclHandler and LexicalHandler. The following code associates a DeclHandler with an XMLReader implementation:

boolean bind (org.xml.sax.XMLReader reader,
              org.xml.sax.DeclHandler handler) {
  boolean result = false;
  try {
    reader.setProperty (
        "http://xml.org/sax/properties/declaration-handler",
        handler);
    result = true;
  }
  catch (org.xml.sax.SAXException sex) { }
  return result;
}

And the following code retrieves the LexicalHandler associated with an XMLReader:

org.xml.sax.Lexicalhandler get (org.xml.sax.XMLReader read) {
  org.xml.sax.LexicalHandler result = null;
  try {
    Object prop = reader.getProperty(
        "http://xml.org/sax/properties/lexical-handler");
    result = (org.xml.sax.Lexicalhandler)prop;
  }
  cath (org.xml.sax.SAXException sex) {}
  return result;
}

Note that neither of these code fragments distinguish between unrecognized properties and recognized but unsupported properties.

Because XMLReader is often implemented by XML parsers, it exposes an overloaded pair of parse methods.

package org.xml.sax;
public interface XMLReader {
       :               :
  void parse (String systemId)
           throws SAXException, java.io.IOException;
  void parse (InputSource source)
           throws SAXException, java.io.IOException;
}

The following code fragment demonstrates using the Apache exrces parser to parse an XML document against a caller-provided ContentHandler:

boolean parseIt (org.xml.sax.ContentHandler handler) {
  boolean result = false;
  try {
    org.xml.sax.XMLReader reader;
    reader = new org.apache.xerces.parsers.SAXparser ();
    reader.setContentHandler (handler);
    reader.parse ("http://www.develop.com/dbox/hom.xml");
    result = true;
  }
  catch (Exception ex) { }
  return result;
}

Note that a call to the String-based parse method

reader.parse("foo.xml");

is equivalent to calling the InputSource-based parse method as follows:

reader.parse(new org.xml.sax.InputSource("foo.xml"));

obviously more convenient.

Most SAX interfaces are amenable to pipeline-style processing, where an implementation of, say, ContentHandler can intercept certain information items it recognizes but pass along unrecognized information items to a downstream processor that also implements ContentHandler. SAX makes this model concrete via its XMLFilter interface. XMLFilter extends the XMLReader interface by adding two methods, one to discover the upstream XMLReader implementation and one to set it. The following is the definition of XMLFilter:

package org.xml.sax;
interface XMLFilter extends XMLReader {
  XMLReader getParent ();
  Void      setParent (XMLReader parent);
}

As shown in Figure 2.3, this interface allows several independent processing components to be chained together with UNIX pipes. To make writing filters easier, SAX provides the XMLFilterImpl helper class that provides default implementations of most methods of the following interfaces: XMLFilter, EntityResolver, DTDHandler, ContentHandler, and ErrorHandler. The implementations of the last four interfaces simply forward the calls to the corresponding objects registered via the setXXXHandler methods.

Figure 2.3Figure 2.3. SAX2 pipelines


As this chapter has shown, SAX is a streaming interface that is designed around a serial stream of method invocations that convey the information items contained in an XML document. For applications that can act upon a document a chunk at a time, this style of interface is ideal, as there is no need to retain the original information items once they have been conveyed via the appropriate handler method. For resource-sensitive applications (e.g., low-memory devices, high-throughput server applications), this is arguably the only way an XML document can be conveyed in memory. However, applications that need to convey an XML document en masse often find SAX bothersome at best and impossible to use at worst. For these applications, the Document Object Model is more appropriate.

  • + Share This
  • 🔖 Save To Your Account