Skip to main content

SAX, the power API

In this preview from XML by Example, compare DOM and SAX and then put SAX to work

Return to article


Listing 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));
   }
}

Return to article