Datasheet

41: XMLEvent evt;
42: while ((evt = pullParser.nextEvent()) != null) {
43: switch (evt.type) {
44: case XMLEvent.ELEMENT :
45: ElementEvent eltEvt = (ElementEvent) evt;
46: if (eltEvt.start) {
47: textStack.push(new StringBuffer());
48: String localPart = eltEvt.element.localpart;
49: if (localPart.equals("book")) {
50: XMLAttributes attrs = eltEvt.attributes;
51: String version =
52: attrs.getValue(null, "version");
53: if (version.equals("1.0")) {
54: book = new Book();
55: continue;
56: }
57: throw new XNIException("bad version");
58: }
If you see a starting ElementEvent for the book element, you check the version attribute to make sure it’s
1.0 and then instantiate a new Book object. For all starting ElementEvents, you push a new StringBuffer
onto a textStack, just like for SAX. You do this to make sure you catch text in mixed content, which will
be interrupted by markup. For example, in
<blockquote>
I really <em>didn’t</em> like what he had to say
</blockquote>
the text "I really" and "like what he had to say" belongs inside the blockquote element, whereas the text
"didn’t" belongs inside the em element. Keeping this text together is what the textStack is all about.
The real work of building the object is done when you hit the end tag, where you get an ending
ElementEvent. Here you grab the text you’ve been collecting for this element and, based on the tag
you’re closing, call the appropriate Book setter method. You should be pretty familiar with this sort of
code by now:
59: } else if (!eltEvt.empty) {
60: String localPart = eltEvt.element.localpart;
61: StringBuffer tos =
62: (StringBuffer) textStack.pop();
63: String text = tos.toString();
64: if (localPart.equals("title")) {
65: book.setTitle(text);
66: } else if (localPart.equals("author")) {
67: book.setAuthor(text);
68: } else if (localPart.equals("isbn")) {
69: book.setIsbn(text);
70: } else if (localPart.equals("month")) {
71: book.setMonth(text);
72: } else if (localPart.equals("year")) {
73: int year = 0;
74: year = Integer.parseInt(text);
75: book.setYear(year);
47
Xerces
01 543555 Ch01.qxd 11/5/03 9:40 AM Page 47