HomeXML Page 5 - XML Parsing With SAX and Xerces (part 1)
Sweeping Up The Mess - XML
So you've already seen how Perl and PHP handle XML data. But you're a Real Programmer, and Real Programmers don't waste time with scripting languages. Nope, you need something a little more powerful, something with more horsepower under the hood. Something written in Java. Something like Xerces.
The example you just saw contains a whole bunch of callback method definitions that don't actually do anything. This merely clutters your code while adding very little by way of functionality. Which is why the guys behind Xerces came up with an alternative to the ContentHandler interface, called the DefaultHandler interface.
This "helper" class implements the ContentHandler class, along with all of its callbacks; however, these callbacks do nothing by default. The developer can then selectively override these empty callbacks as per the requirements of the application - this is more efficient in general, and also results in cleaner code.
Take a look at this version of the previous example, this one built on the DefaultHandler class instead of the ContentHandler class:
import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import
java.io.*;
public class MySecondSaxApp extends DefaultHandler {
// constructor
public MySecondSaxApp (String xmlFile) {
// create a Xerces SAX parser
SAXParser parser = new SAXParser();
// set the content handler
parser.setContentHandler(this);
// parse the document
try {
parser.parse(xmlFile);
} catch
(SAXException e) {
System.err.println (e);
} catch (IOException e)
{
System.err.println (e);
}
}
// call when start elements are
found
public void startElement (String uri, String local, String qName,
Attributes
atts) {
System.out.println ("Found element: " + local);
}
// everything
starts here
public static void main (String[] args) {
MySecondSaxApp mySecondExample
= new MySecondSaxApp(args[0]);
}
}
This example is much more readable than
the previous one, primarily because
the entire set of callbacks defined previously
are conspicuously absent
here. As stated above, these empty callbacks are already
provided by the
DefaultHandler class; a developer only needs to redefine those
which are
actually required by the application.
Note, though, that extending
the DefaultHandler class requires you to add
one more item to your list of includes
at the top of the program:
[code]
import org.xml.sax.helpers.DefaultHandler;
Here's the output:
Found element: inventory
Found element: item
Found element: id
Found element:
name
Found element: supplier
Found element: cost
Found element: quantity
Found
element: item
Found element: id
Found element: name
Found element: supplier
Found
element: cost
Found element: quantity