how to get an instance of an XMLEventAllocator?
I am trying to follow the recommended way of parsing XML with StAX
using sun's Cursor-to-Event Example for Java EE 5. You are supposed to traverse the XML via the Cursor API and allocate an XMLEvent
using an XMLEventAllocator
when necessary.
new
, but the according implementation classes in the JDK are not accessible externally.
After reading the JavaDocs and searching the web I have found literally nothing.
One could implement the XMLEventAllocator
interface from scratch, but it seems really wrong, when there are perfectly good implementations in the JDK, besides not being an expert in StAX
makes it di开发者_JS百科fficult to get it right.I would not use that example as a best practice for using StAX. With StAX you have two approaches XMLStreamReader and XMLEventReader. Both give you an API for accessing the events for a depth-first traversal of an XML document. With XMLStream reader you can request info from the XMLStreamReader based on the event type, and with XMLEventReader you are given objects representing the original event.
I recommend using the XMLStreamReader API directly.
Beyond seconding Blaise's suggestion of just using cursor API directly, even if you do want to use Event API there is absolutely no need to define custom XMLEventAllocation
implementation. You can do that if you want to (like add some data to be passed along with Even objects), but it would be an advanced technique.
So if you want to use Event API, just ask XMLInputFactory to produce XMLEventReader, like so:
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(new FileInputStream("file.xml"));
or if you have an XMLStreamReader:
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(streamReader);
and that's all you need to do.
Boy, I have no idea why tutorial has that silly little piece of code -- it makes no sense whatsoever. :-)
精彩评论