- Event Versus Tree Parsing
- ZwiftBooks and SAX
- SAX and State
- ZwiftBooks and DOM
- The JAXP Factory Model
- Summary
- References
The JAXP Factory Model
Setting up a program to make use of SAX and/or DOM is greatly simplified by the Java API for XML Processing (JAXP), which supports the factory pattern for creating instances of parsers. JAXP uses the same factory pattern we encountered in step 3 of this series, when we used JAXP to create an XSLT transform object.
Here’s the basic idea (see Figure 3):
- An application specifies (to the appropriate factory) the properties of the instance required. For parsers, the primary option is whether the parser will validate against a schema.
- The factory returns an instance that meet the specification, or throws an exception.
- The application commences working with the newly instantiated parser.
Figure 3 JAXP uses the factory pattern to create instances that meet the needs of the application.
A Java main method to instantiate a SAX parser to set up our XML warehouse solution will look like this:
public static void main (String [] args) { String filename = "EuroBooks.xml"; DefaultHandler handler = new SaxIsbnHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); parser.parse(filename, handler); } catch(Exception e) { String errorMessage = "Error parsing " + filename + ": " + e; System.err.println(errorMessage); e.printStackTrace(); } }