简体   繁体   中英

What is the difference between XMLStreamReader and XMLEventReader?

I surf through the web. I found that the XMLStreamReader is Cursor style API for parsing XML . And XMLEventReader is Iterator style API for Parsing XML .Could any one tell me in detail?

Have a look at explanation: https://www.ibm.com/developerworks/library/x-stax1/

Both XMLStreamReader and XMLEventReader allow the application to iterate over the underlying XML stream on its own. The difference between the two approaches lies in how they expose pieces of the parsed XML InfoSet. The XMLStreamReader acts as a cursor that points just beyond the most recently parsed XML token and provides methods for obtaining more information about it. This approach is very memory-efficient as it does not create any new objects. However, business application developers might find XMLEventReader slightly more intuitive because it is actually a standard Java Iterator that turns the XML into a stream of event objects. Each event object in turn encapsulates information pertaining to the particular XML structure it represents. Part 2 of this series will provide a detailed description of the event iterator-based API. As to which API style to use depends on the situation. The event iterator-based API represents a more object-oriented approach than the cursor-based API. As such, it is easier to apply in modular architectures, because the current parser state is reflected in the event object; thus, an application component does not need access to the parser/reader while processing the event. Furthermore, it is possible to create an XMLEventReader from an XMLStreamReader using XMLInputFactory's createXMLEventReader(XMLStreamReader) method.

I think the difference is that the stream reader actually represents the events.

XMLEvent event = eventReader.nextEvent();    
if(event.getEventType() == XMLStreamConstants.START_ELEMENT){
    StartElement startElement = event.asStartElement();
    System.out.println(startElement.getName().getLocalPart());
}

vs

streamReader.next();
if(streamReader.getEventType() == XMLStreamReader.START_ELEMENT){
    System.out.println(streamReader.getLocalName());
}

So an extra event object created each time for the event reader. The overhead might be significant as there are many, many events.

两者之间的一个区别是XMLEventReader支持peek() ,而XMLStreamReader不支持。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM