Datasheet

The startElement callback basically sets things up for new data to be collected each time it sees a new
element. It creates a new currentText StringBuffer for collecting this element’s text content and pushes it
onto the textStack. It also pushes the element’s name on the elementStack for placekeeping. This method
must also do some processing of the attributes attached to the element, because the attributes aren’t
available to the endElement callback. In this case, startElement verifies that you’re processing a version
of the book schema that you understand (1.0).
You can’t do most of the work until you’ve encountered the end tag for an element. At this point, you
will have seen any child elements and you’ve seen all the text content associated with the element. The
following endElement callback does the real heavy lifting. First, it pops the top off the textStack, which
contains the text content for the element it’s processing. Depending on the name of the element being
processed, endElement calls the appropriate setter on the Book instance to fill in the correct field. In the
case of the year, it converts the String into an integer before calling the setter method. After all this,
endElement pops the elementStack to make sure you keep your place.
43:
44: public void endElement(String uri, String localPart,
45: String qName)
46: throws SAXException {
47: String text = textStack.pop().toString();
48: if (localPart.equals("book")) {
49: } else if (localPart.equals("title")) {
50: book.setTitle(text);
51: } else if (localPart.equals("author")) {
52: book.setAuthor(text);
53: } else if (localPart.equals("isbn")) {
54: book.setIsbn(text);
55: } else if (localPart.equals("month")) {
56: book.setMonth(text);
57: } else if (localPart.equals("year")) {
58: int year;
59: try {
60: year = Integer.parseInt(text);
61: } catch (NumberFormatException e) {
62: throw new SAXException("year must be a number");
63: }
64: book.setYear(year);
65: } else if (localPart.equals("publisher")) {
66: book.setPublisher(text);
67: } else if (localPart.equals("address")) {
68: book.setAddress(text);
69: } else {
70: throw new SAXException("Unknown element for book");
71: }
72: elementStack.pop();
73: }
74:
The characters callback is called every time the parser encounters a piece of text content. SAX says that
characters may be called more than once inside a startElement/endElement pair, so the implementation
of characters appends the next text to the currentText StringBuffer. This ensures that you collect all the
text for an element:
11
Xerces
01 543555 Ch01.qxd 11/5/03 9:40 AM Page 11