Datasheet
44: return year;
45: }
46:
47: public void setAddress(String string) {
48: address = string;
49: }
50:
51: public void setAuthor(String string) {
52: author = string;
53: }
54:
55: public void setIsbn(String string) {
56: isbn = string;
57: }
58:
59: public void setMonth(String string) {
60: month = string;
61: }
62:
63: public void setPublisher(String string) {
64: publisher = string;
65: }
66:
67: public void setTitle(String string) {
68: title = string;
69: }
70:
71: public void setYear(int i) {
72: year = i;
73: }
74:
75: public String toString() {
76: return title + " by " + author;
77: }
78: }
SAX
Now that you have a JavaBean for Books, you can turn to the task of parsing XML that uses the book
vocabulary. The SAX API is event driven. As Xerces parses an XML document, it calls methods on one or
more event-handler classes that you provide. The following listing, SAXMain.java, shows a typical
method of using SAX to parse a document. After importing all the necessary classes in lines 8-14, you
create a new XMLReader instance in line 19 by instantiating Xerces’ SAXParser class. You then instanti-
ate a BookHandler (line 20) and use it as the XMLReader’s ContentHandler and ErrorHandler event call-
backs. You can do this because BookHandler implements both the ContentHandler and ErrorHandler
interfaces. Once you’ve set up the callbacks, you’re ready to call the parser, which you do in line 24. The
BookHandler’s callback methods build an instance of Book that contains the information from the XML
document. You obtain this Book instance by calling the getBook method on the bookHandler instance,
and then you print a human-readable representation of the Book using toString.
8
Chapter 1
01 543555 Ch01.qxd 11/5/03 9:40 AM Page 8