SAX and DOM and Rock'n Roll (1/4) - exploring XML
SAX and DOM and Rock'n Roll
or
Life is a Diet when you are an Applet
You WebReference readers are never content. Once you have the desired functionality in place in an applet you wonder whether it could be done in half the space. And you are absolutely right: It can be done! In this column, we'll trim our RSS viewer down to size, and we'll also discuss different XML processing styles along the way.
- The event-driven style: SAX
- The object-driven style: DOM
- SAX vs. DOM
- Simplistic XPath and Conclusion
The SAX2DOM diet
Our formerly latest and greatest version of the RSS viewer applet uses the Aelfred XML parser for parsing the RSS news feed. While this is great for getting off the ground quickly it comes at a price: 23 kilobytes of excess weight.
Like in real life, if you want to lose weight you have to change your life style. For a piece of software that means changing the programming style. In XML programming, two styles dominate: the event-driven style, and the object-driven style.
The event-driven style: SAX
David Megginson, in creating the Aelfred parser, also created an interface implementing an event-driven approach to parsing XML. Whenever the parser encounters an XML tag, it calls a certain function on this interface to inform the hosting application of the event. This interface to the Aelfred parser was taken as a starting point and has since evolved into the Simple API for XML, SAX. Here are the most important functions of the callback interface of Aelfred:
public abstract interface XmlHandler { // called at the beginning of the XML document, useful for initialization void startDocument() throws Exception; // called at the end of the XML document, useful for cleanup void endDocument() throws Exception; // called every time a start tag was encountered, such as <a> void startElement(String tagName) throws Exception; // called every time an end tag was encountered, such as </a> void endElement(String tagName) throws Exception; // called every time an attribute was encountered, such as href="/" void attribute(String name, String value, boolean implicit) throws Exception; // called every time character data (#PCDATA) was encountered void charData(char[] chars, int begin, int end) throws Exception; ... }
All the application programmer has to do is create an implementation of the interface that performs the desired action, such as storing the encountered data in an application-specific data structure. In our case this is the RSSHandler which populates the corresponding elements of the RSSChannel object.
Produced by Michael Claßen
All Rights Reserved. Legal Notices.
URL: https://www.webreference.com/xml/column11/index.html
Created: Apr. 18, 2000
Revised: Apr. 26, 2000