Datasheet
5: * Example from "Professional XML Development with Apache Tools"
6: *
7: */
8: package com.sauria.apachexml.ch1;
9:
10: import java.util.Stack;
11:
12: import org.xml.sax.Attributes;
13: import org.xml.sax.SAXException;
14: import org.xml.sax.SAXParseException;
15: import org.xml.sax.helpers.DefaultHandler;
16:
17: public class BookHandler extends DefaultHandler {
18: private Stack elementStack = new Stack();
19: private Stack textStack = new Stack();
20: private StringBuffer currentText = null;
21: private Book book = null;
22:
23: public Book getBook() {
24: return book;
25: }
26:
We’ll start by looking at the methods you need from the ContentHandler interface. Almost all
ContentHandlers need to manage a stack of elements and a stack of text. The reason is simple. You need
to keep track of the level of nesting you’re in. This means you need a stack of elements to keep track of
where you are. You also need to keep track of any character data you’ve seen, and you need to do this by
the level where you saw the text; so, you need a second stack to keep track of the text. These stacks as
well as a StringBuffer for accumulating text and an instance of Book are declared in lines 18-21. The
accessor to the book instance appears in lines 23-25.
The ContentHandler callback methods use the two stacks to create a Book instance and call the appro-
priate setter methods on the Book. The methods you’re using from ContentHandler are startElement,
endElement, and characters. Each callback method is passed arguments containing the data associated
with the event. For example, the startElement method is passed the localPart namespace URI, and the
QName of the element being processed. It’s also passed the attributes for that element:
27: public void startElement(
28: String uri,
29: String localPart,
30: String qName,
31: Attributes attributes)
32: throws SAXException {
33: currentText = new StringBuffer();
34: textStack.push(currentText);
35: elementStack.push(localPart);
36: if (localPart.equals("book")) {
37: String version = attributes.getValue("", "version");
38: if (version != null && !version.equals("1.0"))
39: throw new SAXException("Incorrect book version");
40: book = new Book();
41: }
42: }
10
Chapter 1
01 543555 Ch01.qxd 11/5/03 9:40 AM Page 10