As you look over this document, you can see that its main function is to take an XML file
from the command line, parse it, and print out the elements that you are looking for. The first
thing you should notice is the following section:
// Get an instance of the SAXParserFactory
SAXParserFactory spf = SAXParserFactory.newInstance();
// Get a SAXParser instance from the factory
SAXParser sp = spf.newSAXParser();
In this section, you are creating a reference to a parser that will be used to actually parse the
XML document. To do this you use the static factory method
SAXParserFactory.newInstance() , which obtains a new instance of a SAXParserFactory .
After you have an instance of a SAXParserFactory , you create a new SAXParser , by calling
the SAXParserFactory.newSAXParser() method. The SAXParser defines the API that wraps
an org.xml.sax.Parser implementation class. By using this class, an application can parse
content using the SAX API.
The next section we need to examine is
// Create an instance of our HandlerBase
SAXHandler handler = new SAXHandler();
This section of code creates an instance of your event handler SAXHandler . To capture events
invoked by the parser, you need to either create a class that implements the
org.xml.sax.DocumentHandler interface or extend the class org.xml.sax.HandlerBase ,
which implements default handlers defined by the DocumentHandler interface. For our exam-
ple, you have extended HandlerBase so you only have to implement the methods you are inter-
ested in handling. This is much like the event handlers of the AWT.
After you have an instance of your event handler, you can start the parser. The snippet for this
// Set the Document handler to call our SAXHandler when
// SAX event occurs while parsing our XMLResource
The SAXParser.parse() method takes an InputSource that contains an XML stream and a
reference to your handler. As the parser parses your XML document, it will trigger events that
will be handled by your SAXHandler , which can be found in Listing 10.3.
L ISTING 10.3