XML technologies / XML / XML in a Nutshell / SAX reference / The package org.xml.sax
(Excerpt from “XML in a Nutshell” by Elliotte Rusty Harold & W. Scott Means)
The package org.xml.sax contains the core of SAX, the interface definitions and classes making up the Simple API for XML.
The Attributes interface
A start-tag’s attribute list is represented by an implementation of the interface Attributes. Attribute order need not match the XML document. Objects of type Attributes are supplied as arguments to the startElement( ) method of the ContentHandler interface. Individual attributes can be accessed in three ways:
by number: its position in the attribute list
by namespace URI and local name
by fully qualified name
Namespace declaration attributes (xmlns and xmlns:präfix) are unavailable this way unless the feature "http://xml.org/sax/features/namespace-prefixes" is enabled. By default, it is false.
If the feature "http://xml.org/sax/features/namespace-prefixes" is false, qualified names may be inaccessible. If the feature "http://xml.org/sax/features/namespaces" is false, local names and namespace URIs may be unavailable.
package org.xml.sax;
public interface Attributes {
public int getLength( );
public String getURI(int index);
public String getLocalName(int index);
public String getQName(int index);
public int getIndex(String uri, String localName);
public int getIndex(String qualifiedName);
public String getType(int index);
public String getType(String uri, String localName);
public String getType(String qualifiedName);
public String getValue(String uri, String localName);
public String getValue(String qualifiedName);
public String getValue(int index);
}
The ContentHandler interface
The interface ContentHandler is the key to SAX. Almost all SAX work requires it. Pass an instance to the XMLReader, the parser, using its method setContentHandler( ). The purpose of ContentHandler is to supply callbacks: as the parser reads the document, it calls the appropriate methods of the ContentHandler to tell the program what it has just read.
package org.xml.sax;
public interface ContentHandler {
public void setDocumentLocator(Locator locator);
public void startDocument( ) throws SAXException;
public void endDocument( ) throws SAXException;
public void startPrefixMapping(String prefix, String uri)
throws SAXException;
public void endPrefixMapping(String prefix) throws SAXException;
public void startElement(String namespaceURI, String localName,
String qualifiedName, Attributes atts) throws SAXException;
public void endElement(String namespaceURI, String localName,
String qualifiedName) throws SAXException;
public void characters(char[] text, int start, int length)
throws SAXException;
public void ignorableWhitespace(char[] text, int start, int length)
throws SAXException;
public void processingInstruction(String target, String data)
throws SAXException;
public void skippedEntity(String name) throws SAXException;
}
The DTDHandler interface
If the method setDTDHandler( ) of XMLReader has received an instance of the DTDHandler interface, the program is notified when the DTD contains declarations of notations and unparsed entities. This information can be saved for later use to investigate unreplaced entities encountered while reading the document:
package org.xml.sax;
public interface DTDHandler {
public void notationDecl(String name, String publicID, String systemID)
throws SAXException;
public void unparsedEntityDecl(String name, String publicID,
String systemID, String notationName) throws SAXException;
}
The EntityResolver interface
Passing the XMLReader an instance of the interface EntityResolver gives control over the parser’s access to external entities, including the external DTD subset. You could replace original entities with others: for example, replace an Internet DTD reference with a local copy, or search a directory for locations using a particular PUBLIC identifier.
package org.xml.sax;
public interface EntityResolver {
public InputSource resolveEntity (String publicID, String systemID)
throws SAXException, IOException;
}
The ErrorHandler interface
An instance of the interface ErrorHandler lets you integrate customized error handling into the XML parser. Give the XMLReader its ErrorHandler by calling the method setErrorHandler( ). For example, make validation errors terminate the program by throwing an exception in the error() method. Each of the interface’s three methods receives a SAXParseException containing details of the error’s cause and location in the XML document:
package org.xml.sax;
public interface ErrorHandler {
public void warning(SAXParseException exception) throws SAXException;
public void error(SAXParseException exception) throws SAXException;
public void fatalError(SAXParseException exception)
throws SAXException;
}Warnings indicate potential problems found by the parser that need not violate well-formedness or validity rules. For example, an xml:lang attribute might lack a valid ISO-639 value. Errors most commonly violate validity rules: the parser should report them but continue processing. Fatal errors affect well-formedness: the parser cannot continue afterward. Some parsers report namespace well-formedness errors as fatal; others treat them as nonfatal.
The Locator interface
Unlike most interfaces in the package org.xml.sax, the Locator is implemented by the parser, not by you. The parser can call the method setDocumentLocator( ) on the ContentHandler instance. This must happen before startDocument( ) is called. Store a reference to the DocumentLocator in a field of your ContentHandler class for later use:
private Locator locator;
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}The saved Locator can be used inside methods such as startElement() or characters() of the actual ContentHandler to determine the current line and column. In the Locator, for example, the current start-tag begins at line 17, column 3 of the URL "http://www.slashdot.org/slashdot.xml":
package org.xml.sax;
public interface Locator {
public String getPublicId( );
public String getSystemId();
public int getLineNumber( );
public int getColumnNumber( );
}
The XMLFilter interface
An XMLFilter is an XMLReader receiving events not from a usual input source such as an InputStream but from another XMLReader. Filters sit between the document and application, modifying XML before handing it over. This interface is rarely implemented directly; using the more complete class org.xml.sax.helpers.XMLFilterImpl is almost always easier.
package org.xml.sax;
public interface XMLFilter extends XMLReader {
public void setParent(XMLReader);
public XMLReader getParent( );
}
The XMLReader interface
The XMLReader is the actual parser, reading and analyzing XML documents. Rather than implementing it yourself, use the class org.xml.sax.helpers.XMLReaderFactory to obtain a parser-specific implementation. Configure it using the various set methods. Finally call a parse() method. The parser reads the supplied document and calls methods of its ContentHandler, its ErrorHandler, its EntityResolver and/or its DTDHandler:
package org.xml.sax;
public interface XMLReader {
public boolean getFeature(String name)
throws SAXNotRecognizedException, SAXNotSupportedException;
public void setFeature(String name, boolean value)
throws SAXNotRecognizedException, SAXNotSupportedException;
public Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException;
public void setProperty(String name, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException;
public void setEntityResolver(EntityResolver resolver);
public EntityResolver getEntityResolver( );
public void setDTDHandler(DTDHandler handler);
public DTDHandler getDTDHandler( );
public void ssetContentHandler(ContentHandler handler);
public ContentHandler getContentHandler( );
public void setErrorHandler(ErrorHandler handler);
public ErrorHandler getErrorHandler( );
public void parse(InputSource input) throws IOException, SAXException;
public void parse(String systemID) throws IOException, SAXException;
}
The InputSource class
The class InputSource abstracts a source supplying an XML document’s raw bytes. An InputSource instance can hide a SYSTEM identifier, a PUBLIC identifier, an InputStream and/or a Reader. When the parser receives an InputSource, it tries to read from the Reader. If the InputSource has no Reader, the parser tries the InputStream, taking the specified character encoding into account. If none is specified, it must identify the encoding itself by analyzing the XML declaration. Finally, if neither a Reader nor an InputStream is available, it connects to the URL in the SYSTEM identifier.
package org.xml.sax;
public class InputSource {
public InputSource( );
public InputSource(String systemID);
public InputSource(InputStream byteStream);
public InputSource(Reader reader);
public void setPublicId(String publicID);
public String getPublicId( );
public void setSystemId(String systemID);
public String getSystemId( );
public void setByteStream(InputStream byteStream);
public InputStream getByteStream( );
public void setEncoding(String encoding);
public String getEncoding( );
public void setCharacterStream(Reader reader);
public Reader getCharacterStream( );
}
The SAXException class
Most exceptions thrown by SAX methods are instances of the class SAXException or its subclasses. The sole exception is the method parse() of the XMLReader, which can throw an IOException for I/O problems, such as a dropped TCP connection while reading a document over the Internet.
A SAXException inherits standard exception methods from its superclass, including getMessage() and printStackTrace(). In addition, SAXException also provides the method getException( ), which wraps another exception representing the actual cause of a problem:
package org.xml.sax;
public class SAXException extends Exception {
public SAXException(String message);
public SAXException(Exception ex);
public SAXException(String message, Exception ex);
public String getMessage( );
public Exception getException( );
public String toString( );
}
SAXParseException
A parser detecting a well-formedness violation throws a SAXParseException. The SAXParseException is a subclass of SAXException and is also passed to the ErrorHandler. The ErrorHandler decides whether to interrupt the parser by throwing the exception or ignore the error.
Besides its superclass’s methods, SAXParseException provides methods to query line and column numbers and SYSTEM and PUBLIC identifiers of the document where the error occurred:
package org.xml.sax;
public class SAXParseException extends SAXException {
public SAXParseException(String message, Locator locator);
public SAXParseException(String message, Locator locator, Exception e);
public SAXParseException(String message,
String publicID, String systemID, int lineNumber, int columnNumber);
public SAXParseException(String message,
String publicID, String systemID, int lineNumber, int
columnNumber, Exception e);
public String getPublicId( );
public String getSystemId( );
public int getLineNumber( );
public int getColumnNumber( );
}
SAXNotRecognizedException
A SAXNotRecognizedException is thrown when you try to set an unknown property or feature. Apart from its constructor, it only has its superclass’s methods:
package org.xml.sax;
public class SAXNotRecognizedException extends SAXException {
public SAXNotRecognizedException( );
public SAXNotRecognizedException(String message);
}
SAXNotSupportedException
The SAXNotSupportedException is used when the parser recognizes a feature or property but cannot read or set it, or when the proposed value is not permitted. It too has only one constructor and the methods of its superclass:
package org.xml.sax;
public class SAXNotSupportedException extends SAXException {
public SAXNotSupportedException( );
public SAXNotSupportedException(String message);
}
Copyright © 2005 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “XML in a Nutshell” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de