Home > Articles > Programming > Java

Alternative API: SAX

This chapter is from the book

This chapter is from the book

Maintaining the State

Listing 8.1 is convenient for a SAX parser because the information is stored as attributes of price elements. The application had to register only for startElement().

Listing 8.3 is more complex because the information is scattered across several elements. Specifically, vendors have different prices depending on the delivery delay. If the user is willing to wait, he or she may get a better price. Figure 8.6 illustrates the structure of the document.

Listing 8.3: xtpricelist.xml

<?xml version="1.0"?>
<xbe:price-list xmlns:xbe="http://www.psol.com/xbe2/listing8.3">
  <xbe:name>XML Training</xbe:name>
  <xbe:vendor>
   <xbe:name>Playfield Training</xbe:name>
   <xbe:price-quote delivery="5">999.00</xbe:price-quote>
   <xbe:price-quote delivery="15">899.00</xbe:price-quote>
  </xbe:vendor>
  <xbe:vendor>
<xbe:name>XMLi</xbe:name>
    <xbe:price-quote delivery="3">2999.00</xbe:price-quote>
   <xbe:price-quote delivery="30">1499.00</xbe:price-quote>
   <xbe:price-quote delivery="45">699.00</xbe:price-quote>
  </xbe:vendor>
  <xbe:vendor>
   <xbe:name>WriteIT</xbe:name>
   <xbe:price-quote delivery="5">799.00</xbe:price-quote>
   <xbe:price-quote delivery="15">899.00</xbe:price-quote>
  </xbe:vendor>
  <xbe:vendor>
   <xbe:name>Emailaholic</xbe:name>
   <xbe:price-quote delivery="1">1999.00</xbe:price-quote>
  </xbe:vendor>
</xbe:price-list>
Figure 8.6: Price list structure.

To find the best deal, the application must collect information from several elements. However, the parser can generate up to three events for each element (startElement(), characters(), and endElement()). The application must somehow relate events and elements.

» See the section "Managing the State" in Chapter 7 for a discussion of state (page 234).

The example in this section achieves the same result but for a SAX parser.

Listing 8.4 is a new Java application that looks for the best deal in the price list. When looking for the best deal, it takes the urgency into consideration. Indeed, from Listing 8.3, the cheapest vendor (XMLi) is also the slowest. On the other hand, Emailaholic is expensive, but it delivers in two days.

Listing 8.4: BestDeal.java

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

package com.psol.xbe2;

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

/**
 * This class receives events from the SAX2Internal adapter
 * and does the comparison required.
 * This class holds the "business logic."
 * SAX event handling is done in an inner class.
 */

public class BestDeal
{
  /**
  * SAX event handler to adapt from the SAX interface to
  * best deal data structure.
  */

  protected class SAX2BestDeal
   extends DefaultHandler
  {
   /**
    * constants
    */

   /**
    * state constants
    */
   final protected int START = 0,
             PRICE_LIST = 1,
             PRICE_LIST_NAME = 2,
             VENDOR = 3,
             VENDOR_NAME = 4,
             VENDOR_PRICE_QUOTE = 5;

   /**
    * the current state
    */
   protected int state = START; 

   /**
    * current leaf element and current vendor
    */
   protected String vendorName = null;
   protected StringBuffer buffer = null;
   protected int delivery = Integer.MAX_VALUE;

   /**
    * startElement event
    * @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)
     throws SAXException
   {
     if(!uri.equals(NAMESPACE_URI))
      return;
     // this accept many combinations of elements
     // it would work if new elements were being added, etc.
     // this ensures maximal flexibility: if the document
     // has to be validated, use a validating parser
     switch(state)
     {
      case START:
        if(name.equals("price-list"))
         state = PRICE_LIST;
        break;
      case PRICE_LIST:
        if(name.equals("name"))
        {
         state = PRICE_LIST_NAME;
         buffer = new StringBuffer();
        }
        if(name.equals("vendor"))
         state = VENDOR;
        break;
      case VENDOR:
        if(name.equals("name"))
        {
         state = VENDOR_NAME;
         buffer = new StringBuffer();
        }
        if(name.equals("price-quote"))
        {
         state = VENDOR_PRICE_QUOTE;
         String st = attributes.getValue("","delivery");
         delivery = Integer.parseInt(st);
         buffer = new StringBuffer();
        }
        break; 
     }
   }

   /**
    * content of the element
    * @param chars documents characters
    * @param start first character in the content
    * @param length last character in the content
    */
   public void characters(char[] chars,int start,int length)
   {
     switch(state)
     {
      case PRICE_LIST_NAME:
      case VENDOR_NAME:
      case VENDOR_PRICE_QUOTE:
        buffer.append(chars,start,length);
        break;
     }
   }

   /**
    * endElement event
    * @param uri namespace URI
    * @param name local name
    * @param qualifiedName qualified name (with prefix)
    */
   public void endElement(String uri,
               String name,
               String qualifiedName)
   {
     if(!uri.equals(NAMESPACE_URI))
      return;
     switch(state)
     {
      case PRICE_LIST_NAME:
        if(name.equals("name"))
        {
         state = PRICE_LIST;
         setProductName(buffer.toString());
         buffer = null;
        }
        break;
      case VENDOR_NAME:
        if(name.equals("name"))
        {
         state = VENDOR;
         vendorName = buffer.toString();
         buffer = null; 
        }
        break;
      case VENDOR_PRICE_QUOTE:
        if(name.equals("price-quote"))
        {
         state = VENDOR;
         double price = 0.0;
         Double stringDouble =
           Double.valueOf(buffer.toString());
         if(null != stringDouble)
           price = stringDouble.doubleValue();
         compare(vendorName,price,delivery);
         delivery = Integer.MAX_VALUE;
         buffer = null;
        }
        break;
      case VENDOR:
        if(name.equals("vendor"))
        {
         state = PRICE_LIST;
         vendorName = null;
        }
        break;
      case PRICE_LIST:
        if(name.equals("price-list"))
         state = START;
        break;
     }
   }
  }

  /**
  * constant
  */
  protected static final String
   MESSAGE =
     "The best deal is proposed by {0}. " +
     "A(n) {1} delivered in {2,number,integer} days for " +
     "{3,number,currency}",
   NAMESPACE_URI = "http://www.psol.com/xbe2/listing8.3",
   PARSER_NAME = "org.apache.xerces.parsers.SAXParser";

  /**
  * properties we are collecting: best price, delivery time,
  * product and vendor names
  */
  public double price = Double.MAX_VALUE;
  public int delivery = Integer.MAX_VALUE;
  public String product = null,
         vendor = null;

  /**
  * target delivery value (refuse elements above this target)
  */
  protected int targetDelivery;

  /**
  * creates a BestDeal
  * @param td the target for delivery
  */
  public BestDeal(int td)
  {
   targetDelivery = td;
  }

  /**
  * called by SAX2Internal when it has found the product name
  * @param name the product name
  */
  public void setProductName(String name)
  {
   product = name;
  }

  /**
  * called by SAX2Internal when it has found a price
  * @param vendor vendor's name
  * @param price price proposal
  * @param delivery delivery time proposal
  */
  public void compare(String vendor,double price,int delivery)
  {
   if(delivery <= targetDelivery)
   {
     if(this.price > price)
     {
      this.price = price;
      this.vendor = vendor;
      this.delivery = delivery; 
     }
   }
  }

  /**
  * return a ContentHandler that populates this object
  * @return the ContentHandler
  */
  public ContentHandler getContentHandler()
  {
   return new SAX2BestDeal();
  }

  /**
  * 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
  {
   if(args.length < 2)
   {
     System.out.println(
      "java com.psol.xbe2.BestDeal file delivery");
     return;
   }

   BestDeal bestDeal = new BestDeal(Integer.parseInt(args[1]));

   XMLReader parser =
     XMLReaderFactory.createXMLReader(PARSER_NAME);
   parser.setContentHandler(bestDeal.getContentHandler());
   parser.parse(args[0]);

   Object[] objects = new Object[]
   {
     bestDeal.vendor,
     bestDeal.product,
     new Integer(bestDeal.delivery),
     new Double(bestDeal.price)
   };
   System.out.println(MessageFormat.format(MESSAGE,objects)); 
  }
}

You compile and run this application like the Cheapest application introduced previously. The results depend on the urgency of the delivery. You will notice that this program takes two parameters: the filename and the longest delay one is willing to wait.

java com.psol.xbe2.BestDeal data/xtpricelist.xml 60

returns

The best deal is proposed by XMLi. A(n) XML Training delivered
in 45 days for $699.00

whereas

java com.psol.xbe2.BestDeal data/xtpricelist.xml 3

returns

The best deal is proposed by Emailaholic. A(n) XML Training
delivered in 1 day for $1,999.00

A Layered Architecture

Listing 8.4 is the most complex application you have seen so far. It's not abnormal: The SAX parser is very low level so the application has to take over a lot of the work that a DOM parser would do.

The application is organized around two classes: SAX2BestDeal and BestDeal. SAX2BestDeal manages the interface with the SAX parser. It manages the state and groups events in a coherent way.

BestDeal has the logic to perform price comparison. It also maintains information in a structure that is optimized for the application, not XML. The architecture for this application is illustrated in Figure 8.7. Figure 8.8 shows the class diagram in UML.

Figure 8.7: The architecture for the application.

Figure 8.8: The class diagram for the application.

SAX2BestDeal handles several events: startElement(), endElement(), and characters(). All along, SAX2BestDeal tracks its position in the document tree.

For example, in a characters() event, SAX2BestDeal needs to know whether the text is a name, the price, or whitespaces that can be ignored. Furthermore, there are two name elements: the price-list's name and the vendor's name.

States

A SAX parser, unlike a DOM parser, does not provide state information. The application is responsible for tracking its own state.

There are several options for this. In Listing 8.4, we identified the meaningful states and the transitions between them. It's not difficult to derive this information from the document structure in Figure 8.6.

It is obvious that the application will first encounter a price-list tag. The first state should, therefore, be "within a price-list." From there, the application will reach a name. The second state is therefore "within a name in the price-list."

The next element has to be a vendor, so the third state is "within a vendor in the price-list." The fourth state is "within a name in a vendor in a price-list," because a name follows the vendor.

The name is followed by a price-quote element and the corresponding state is "in a price in a vendor in a price-list." Afterward, the parser encounters either a price-quote or a vendor for which there are already states.

It's easier to visualize this concept on a graph with states and transitions, such as the one shown in Figure 8.9. Note that there are two different states related to two different name elements, depending on whether you are dealing with the price-list/name or price-list/vendor/name.

Figure 8.9: State transition diagram.

In Listing 8.4, the state variable stores the current state:

final protected int START = 0,
          PRICE_LIST = 1,
          PRICE_LIST_NAME = 2,
          VENDOR = 3,
          VENDOR_NAME = 4,
          VENDOR_PRICE_QUOTE = 5;
protected int state = START; 

Transitions

  1. The value of the state variable changes in response to events. In the example, elementStart() updates the state:

  2.    ifswitch(state)
       {
        case START:
          if(name.equals("price-list"))
           state = PRICE_LIST;
          break;
        case PRICE_LIST:
          if(name.equals("name"))
           state = PRICE_LIST_NAME;
           // ...
          if(name.equals("vendor"))
           state = VENDOR;
         break;
        case VENDOR:
          if(name.equals("name"))
           state = VENDOR_NAME;
           // ...
          if(name.equals("price-quote"))
           state = VENDOR_PRICE_QUOTE;
           // ...
          break;
       }

    SAX2BestDeal has a few instance variables to store the content of the current name and price-quote. In effect, it maintains a small subset of the tree. Note that, unlike DOM, it never has the entire tree because it discards the name and price-quote when the application has used them.

    This is very efficient memorywise. In fact, you could process a file of several gigabytes because, at any point, there's only a small subset in memory.

  3. The parser calls characters() for every character data in the document, including indenting. It makes sense to record text only in name and price-quote, so the event handler uses the state.

  4.    switch(state)
       {
        case PRICE_LIST_NAME:
        case VENDOR_NAME:
        case VENDOR_PRICE_QUOTE:
          buffer.append(chars,start,length);
          break;
       }
  5. The event handler for endElement() updates the state and calls BestDeal to process the current element:

  6.    switch(state)
       {
        case PRICE_LIST_NAME:
          if(name.equals("name"))
          {
           state = PRICE_LIST;
           setProductName(buffer.toString());
           // ...
          }
          break;
        case VENDOR_NAME:
          if(name.equals("name"))
           state = VENDOR;
           // ...
          break;
        case VENDOR_PRICE_QUOTE:
          if(name.equals("price-quote"))
          {
           state = VENDOR;
           // ...
           compare(vendorName,price,delivery);
           // ...
          }
          break;
        case VENDOR:
          if(name.equals("vendor"))
           state = PRICE_LIST;
           // ...
          break;
        case PRICE_LIST:
          if(name.equals("price-list"))
           state = START;
          break;
       }

NOTE

An alternative to using a state variable is to use a Stack. Push the element name (or another identifier) in startElement() and pop it in endElement().

Lessons Learned

Listing 8.4 is typical for a SAX application. There's a SAX event handler (SAX2BestDeal) which packages the events in the format most suitable for the application.

The application logic (in BestDeal) is kept separated from the event handler. In fact, in many cases, the application logic will be written independently of XML.

The layered approach establishes a clean-cut separation between the application logic and the parsing.

The example also clearly illustrates that SAX is more efficient than DOM but that it requires more work from the programmer. In particular, the programmer has to explicitly manage states and transitions between states. In DOM, the state was implicit in the recursive walk of the tree.

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