- Alternative API: SAX
- SAX: The Power API
- Commonly Used SAX Interfaces and Classes
- Maintaining the State
- Flexibility
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
The value of the state variable changes in response to events. In the example, elementStart() updates the state:
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.
The event handler for endElement() updates the state and calls BestDeal to process the current element:
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.
switch(state) { case PRICE_LIST_NAME: case VENDOR_NAME: case VENDOR_PRICE_QUOTE: buffer.append(chars,start,length); break; }
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.