Datasheet

1: /*
2: *
3: * SAXMain.java
4: *
5: * Example from "Professional XML Development with Apache Tools"
6: *
7: */
8: package com.sauria.apachexml.ch1;
9:
10: import java.io.IOException;
11:
12: import org.apache.xerces.parsers.SAXParser;
13: import org.xml.sax.SAXException;
14: import org.xml.sax.XMLReader;
15:
16: public class SAXMain {
17:
18: public static void main(String[] args) {
19: XMLReader r = new SAXParser();
20: BookHandler bookHandler = new BookHandler();
21: r.setContentHandler(bookHandler);
22: r.setErrorHandler(bookHandler);
23: try {
24: r.parse(args[0]);
25: System.out.println(bookHandler.getBook().toString());
26: } catch (SAXException se) {
27: System.out.println("SAX Error during parsing " +
28: se.getMessage());
29: se.printStackTrace();
30: } catch (IOException ioe) {
31: System.out.println("I/O Error during parsing " +
32: ioe.getMessage());
33: ioe.printStackTrace();
34: } catch (Exception e) {
35: System.out.println("Error during parsing " +
36: e.getMessage());
37: e.printStackTrace();
38: }
39: }
40: }
The real work in a SAX-based application is done by the event handlers, so let’s turn our attention to the
BookHandler class and see what’s going on. The following BookHandler class extends SAX’s
DefaultHandler class. There are two reasons. First, DefaultHandler implements all the SAX callback han-
dler interfaces, so you’re saving the effort of writing all the implements clauses. Second, because
DefaultHandler is a class, your code doesn’t have to implement every method in every callback inter-
face. Instead, you just supply an implementation for the methods you’re interested in, shortening the
class overall.
1: /*
2: *
3: * BookHandler.java
4: *
9
Xerces
01 543555 Ch01.qxd 11/5/03 9:40 AM Page 9