Last Updated:

Reading an XML File in Java using StAX

Theoretical information about the Java StAX API

The Java StAX or Java Streaming API for XML provides an API for processing XML in Java. StAX consists of two sets of APIs: iterator-based and cursor-based.

  • The cursor-based API allows an application to process XML as an event stream: the application can check the state of the parser and get information about the last event being parsed, and then move on to the next event, and so on. It is a low-level API that does not provide an abstraction over the XML structure.
  • The second set is a high-level iterator-based API. This API allows an application to process XML as a series of event objects, each representing a portion of the XML structure. For each event that you parse, you need to determine the type, as well as disassemble the event into its constituent blocks.

Using the Java StAX API to parse an XML file

Java StAX provides factory methods for creating by which we can represent any element of an XML file as .XMLEventReaderXMLEvent

The most useful methods of the class are the method , which are responsible for determining the start and end tags.XMLEventisStartElement()isEndElement()

Below is the XML we'll be pitting Java StAX against:

The following is a listing of the class for reading an XML file:


As you can see from the listing, we parse the XML file into a list of Student objects using the . The result of the program is presented below:


XML File in Java using StAX

If you're interested in reading a file using the Parser DOM