Java StAX Parser Example to read XML file

We can use Java StAX parser to read XML file. Java Streaming API for XML (Java StAX) provides implementation for processing XML in java. StAX consists of two sets of API – cursor based API and iterator based API.

Java StAX

Java StAX cursor based API allows the application to process XML as a stream of tokens aka events; the application can check the parser’s state and get information about the last parsed event, then advance to the next event, and so on. This is a low-level API; while considerably efficient, it does not provide an abstraction of the underlying XML structure.

The higher-level iterator-based API allows the application to process XML as a series of event objects, each of which communicates a piece of the XML structure to the application. All the application needs to do is determine the type of the parsed event, cast it to the corresponding type, and use its methods to get information related to the event.

In this tutorial we will learn how to read XML iteratively using Java StAX. It provides factory methods to create XMLEventReader object using which we can read the xml elements as XMLEvent. Some useful methods in XMLEvent implementation are isStartElement() and isEndElement() to determine whether it’s start tag or end tag.

In last tutorial, we learned how to write xml file in java using java StAX Iterator API.

For this tutorial we have following XML file that contains list of Employee, we will use Java StAX Iterator API to read XML file and create list of Employee object.

employee.xml

To read this XML into Employees list, we will create Employee bean first.

Employee.java

Java StAX Parser Example to read XML file

Here is the program that reads the xml file and create employees list.

StaxXMLReader.java

When we execute above program, we get following output in console.

That’s all for a quick Java StAX parser example to read XML file.

By admin

Leave a Reply

%d bloggers like this: