Beginning SAX

This chapter explores SAX through some progressively more functional examples, which build on each other to present the key concepts that are discussed later in more detail. Essential producer and consumer interfaces are presented together to show how they interact, and you’ll see how to customize classic SAX configurations. We’ll focus first on the producer side, saving most details about consumer-side APIs for a bit later.

How Do the Parts Fit Together?

In the simplest possible example, you (in your role as director) will get an XML parser, which will later produce parsing events. Then you will get a consumer and connect it to the producer for processing the most important events. Finally, you’ll ask that parser to produce events, pushing them through to the consumer.

To start, focus on what the different parts are, and how they relate to each other. Example 2-1 is a simple SAX program, which you can compile and run if you like.

Example 2-1. SAX2 application skeleton

import java.io.IOException; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; public class Skeleton { // argv[0] must be the absolute URL of an XML document public static void main (String argv []) { XMLReader producer; DefaultHandler consumer; // Get an instance of the default XML parser class try { producer = XMLReaderFactory.createXMLReader (); } catch (SAXException e) { System.err.println ( "Can't get parser, check configuration: " + e.getMessage ...

Get SAX2 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.