Home > Articles > Programming > Java

Alternative API: SAX

This chapter is from the book

This chapter is from the book

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 URI—similar to namespaces—and 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
}

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020