Datasheet

76: } else if (localPart.equals("publisher")) {
77: book.setPublisher(text);
78: } else if (localPart.equals("address")) {
79: book.setAddress(text);
80: }
When you see a CharactersEvent, you’re appending the characters in the event to the text you’re keeping
for this element:
81: }
82: break;
83: case XMLEvent.CHARACTERS :
84: CharactersEvent chEvt = (CharactersEvent) evt;
85: StringBuffer tos =
86: (StringBuffer) textStack.peek();
87: tos.append(chEvt.text.toString());
88: break;
89: }
90: }
91: return book;
92: }
93: }
As you can see, the style inside the constructor method is somewhat reminiscent of a SAX content han-
dler. The difference is that when you get to contained objects, the code is dramatically simpler. You just
have a bunch of methods that look like makeBook, except that as part of the processing of certain end
ElementEvents, there’s a call to the constructor function of another class, with the only argument being
the pull parser.
As we’re writing this, the first public review of JSR-173, the Streaming API for XML, has just begun.
Perhaps by the time you’re reading this, NekoXNI’s pull parser will be implementing what’s in that JSR.
At the moment, the NekoXNI tools are separate from Xerces, but there have been some discussions
about incorporating all or some of the tools into the main Xerces distribution.
Practical Usage
We’ve covered a lot of ways you can use Xerces to get information out of XML documents and into your
application. Here are two more practical usage tips.
Xerces isn’t thread safe. You can’t have two threads that execute a single Xerces instance at the same
time. If you’re in a multithreaded situation, you should create one instance of Xerces for each thread. If
for some reason you don’t want to do that, make sure the access to the parser instance is synchronized,
or you’ll run into some nasty problems. A common solution pattern for concurrent systems is to provide
the thread with a pool of parser instances that have already been created.
That leads us into the second tip. If your application is processing many XML documents, you should
try to reuse parser instances. Both the Xerces SAXParser and DOMParser provide a method called reset
that you can use to reset the parser’s internal data structures so the instance can be used to parse another
48
Chapter 1
01 543555 Ch01.qxd 11/5/03 9:40 AM Page 48