Home > Articles > Programming > Java

Alternative API: SAX

This chapter is from the book

This chapter is from the book

SAX: The Power API

SAX was developed by the members of the XML-DEV mailing list as a standard and simple API for event-based parsers. SAX is short for the Simple API for XML.

SAX was originally defined for Java but it is also available for Python, Perl, C++, and COM (Windows objects). More language bindings are sure to follow. Furthermore, through COM, SAX parsers are available to all Windows programming languages, including Visual Basic and Delphi.

Currently SAX is edited by David Megginson (but he has announced that he will retire) and published at http://www.megginson.com/SAX. Unlike DOM, SAX is not endorsed by an official standardization body, but it is widely used and is considered a de facto standard.

As you have seen, in a browser DOM is preferred API. Therefore, the examples in this chapter are written in Java. If you feel you need a crash course on Java, turn to Appendix A.

Some parsers that support SAX include Xerces, the Apache parser— formerly the IBM parser (available from xml.apache.org); MSXML, the Microsoft parser (available from msdn.microsoft.com); and XDK, the Oracle parser (available from technet.oracle.com/tech/xml). These parsers are the most flexible because they also support DOM.

A few parsers offer only SAX, such as James Clark's XP (available from http://www.jclark.com), Ælfred (available from home.pacbell.net/david-b/xml), and ActiveSAX from Vivid Creations (available from http://www.vivid-creations.com).

Getting Started with SAX

Listing 8.2 is a Java application that finds the cheapest offering in Listing 8.1. The application prints the best price and the name of the vendor.

Listing 8.2: Cheapest.java

/*
 * XML By Example, chapter 8: SAX
 */

package com.psol.xbe2;

import org.xml.sax.*;
import java.io.IOException;
import org.xml.sax.helpers.*;
import java.text.MessageFormat;

/**
 * SAX event handler to find the cheapest offering in a list of
 * prices.
 */

public class Cheapest
  extends DefaultHandler
{
  /**
  * constants
  */
  protected static final String
   NAMESPACE_URI = "http://www.psol.com/xbe2/listing8.1",
   MESSAGE =
     "The cheapest offer is from {0} ({1,number,currency})",
   PARSER_NAME = "org.apache.xerces.parsers.SAXParser";

  /**
  * properties we are collecting: cheapest price & vendor
  */
  protected double min = Double.MAX_VALUE;
  protected String vendor = null;
  /**
  * startElement event: the price list is stored as price
  * elements with price and vendor attributes
  * @param uri namespace URI
  * @param name local name
  * @param qualifiedName qualified name (with prefix)
  * @param attributes attributes list
  */
  public void startElement(String uri,
              String name,
              String qualifiedName,
              Attributes attributes)
  {
   if(uri.equals(NAMESPACE_URI) && name.equals("price-quote"))
   {
     String attribute =
      attributes.getValue("","price");
     if(null != attribute)
     {
      double price = toDouble(attribute);
      if(min > price)
      {
        min = price; 
        vendor = attributes.getValue("","vendor");
      }
     }
   }
  }

  /**
  * helper method: turn a string in a double
  * @param string number as a string
  * @return the number as a double, or 0.0 if it cannot convert
  * the number
  */
  protected static final double toDouble(String string)
  {
   Double stringDouble = Double.valueOf(string);
   if(null != stringDouble)
     return stringDouble.doubleValue();
   else
     return 0.0;
  }

  /**
  * main() method
  * decodes command-line parameters and invoke the parser
  * @param args command-line argument
  * @throw Exception catch-all for underlying exceptions
 */
  public static void main(String[] args)
   throws IOException, SAXException
  {
   // command-line arguments
   if(args.length < 1)
   {
     System.out.println("java com.psol.xbe2.Cheapest file");
     return;
   }

   // creates the event handler
   Cheapest cheapest = new Cheapest();

   // creates the parser
   XMLReader parser =
     XMLReaderFactory.createXMLReader(PARSER_NAME);
   parser.setFeature("http://xml.org/sax/features/namespaces",
            true);
   parser.setContentHandler(cheapest);

   // invoke the parser against the price list
   parser.parse(args[0]);

   // print the results
   Object[] objects = new Object[]
   {
     cheapest.vendor,
     new Double(cheapest.min)
   };
   System.out.println(MessageFormat.format(MESSAGE,objects));
  }
}

Compiling the Example

To compile this application, you need a Java Development Kit (JDK) for your platform. For this example, the Java Runtime is not enough. You can download the JDK from java.sun.com.

You must also download the listings available from http://www.marchal.com or http://www.quepublishing.com. The download includes Xerces. As always, I will post updates, if appropriate, on the Web site.

If you have problems with a listing, make sure you visit http://www.marchal.com or http://www.quepublishing.com.

Save Listing 8.2 in a file called Cheapest.java. Go to the DOS prompt, change to the directory where you saved Cheapest.java and compile by issuing the following commands at the DOS prompt:

mkdir classes
set classpath=classes;lib\xerces.jar
javac -d classes src\Cheapest.java

The compilation will install the Java program in the classes directory. These commands assume that you have installed Xerces in the lib directory and Listing 8.2 in the src directory. You might have to adapt the classpath (second command) if you installed the parser in a different directory.

To run the application against the price list, issue the following command:

java com.psol.xbe2.Cheapest data\pricelist.xml

CAUTION

Be warned that Java has difficulty with paths containing spaces. If Cheapest complains that it cannot find the file, check that the directory does not contain a space somewhere.

The result should be

The cheapest offer is from XMLi ($699.00)

This command assumes that Listing 8.1 is in a file called data\pricelist.xml. Again, you might need to adapt the path to your system.

CAUTION

The programs in this chapter do essentially no error checking. It simplifies them and helps concentrate on the XML aspects. It also means that if you type incorrect parameters, they crash.

Remember that you cannot compile this example unless you have installed a Java Development Kit.

Finally, an error such as

src\Cheapest.java:7: Package org.xml.sax not found in import.import org.xml.sax.*;

or

Can't find class com/psol/xbe2/Cheapest or something it requires

is most likely one of the following:

  • The classpath (second command, classes;lib\xerces.jar) is incorrect.

  • You entered an incorrect class name in the last command (com.psol.xbe2.Cheapest).

The Event Handler Step by Step

Events in SAX are defined as methods attached to specific Java interfaces. In this section, we will review Listing 8.2 step by step. The following section gives you more information on the main SAX interfaces.

The easiest solution to declare an event handler is to inherit from the SAX-provided DefaultHandler:

public class Cheapest
  extends DefaultHandler

This application implements only one event handler: startElement() which the parser calls when it encounters a start tag. The parser will call startElement() for every start tag in the document: <xbe:price-list>, <xbe:product> and <xbe:price-quote>.

In Listing 8.2, the event handler is only interested in price-quote, so it tests for it. The handler does nothing with events for other elements:

if(uri.equals(NAMESPACE_URI) && name.equals("price-quote"))
{
  // ...
}

TIP

Note that this is an event handler. It does not call the parser. In fact, it's just the opposite: the parser calls it.

If you're confused, think of AWT events. An event handler attached to, say, a button does not call the button. It waits for the button to be clicked.

When it finds a price-quote element, the event handler extracts the vendor name and the price from the list of attributes. Armed with this information, finding the cheapest product is a simple comparison:

String attribute =
  attributes.getValue("","price");
if(null != attribute)
{
  double price = toDouble(attribute);
  if(min > price)
  {
   min = price;
   vendor = attributes.getValue("","vendor");
  }
}

Notice that the event handler receives the element name, namespace and attribute lists as parameters from the parser.

Let's now turn our attention to the main() method. It creates an event- handler object and a parser object:

Cheapest cheapest = new Cheapest();
XMLReader parser =
  XMLReaderFactory.createXMLReader(PARSER_NAME);

XMLReader and XMLReaderFactory are defined by SAX. An XMLReader is a SAX parser. The factory is a helper class to create XMLReaders.

main() sets a parser feature to request namespace processing and it registers the event handler with the parser. Finally, main() calls the parse() method with the URI to the XML file:

parser.setFeature("http://xml.org/sax/features/namespaces",true);
parser.setContentHandler(cheapest);
parser.parse(args[0]);

TIP

It is not required to set http://xml.org/sax/features/namespaces to true because the default value is true. However, I find it makes the code more readable.

The innocent-looking parse() method triggers parsing of the XML document which, in turn, calls the event handler. It is during the execution of this method that our startElement() method will be called. There's a lot happening behind the call to parse()!

Last but not least, main() prints the result:

Object[] objects = new Object[]
{
  cheapest.vendor,
  new Double(cheapest.min)
};
System.out.println(MessageFormat.format(MESSAGE,objects));

Wait! When do Cheapest.vendor and Cheapest.min acquire their values? We don't set them explicitly in main()! True; it's the event handler job. And the event handler is ultimately called by parse(). That's the beauty of event processing.

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