How to read XML using STAX parser

STAX is yet another parser for reading and parsing XML documents in Java, it is very similar to SAX where they both parse the XML document on call and provide events to the developer in order to handle each read tag separately, unlike DOM which stores the XML as a document in the memory.

The main difference between SAX and STAX is that the former pushes the events to the developer through callback methods defined inside a handler while the latter allows the developer to pull events on request.

In this tutorial, we provide an example for parsing an XML document called Students.xml using STAX parser.

If you’re interested in SAX or DOM parser, please refer to these tutorials: SAX parser, DOM parser.

1- Students.xml

Consider we have the following Students.xml file:

2- Student.java

For mapping purposes, we create Student.java for populating each student element inside Students.xml:

3- STAX parser

In this section, we’re going to parse students.xml and populate a List of Student objects out of it.

STAX parses documents through event readers, each event refers to a read element. There are mainly 3 event types:

  • START_ELEMENT: This event means that the parser starts parsing a new element in the document.
  • END_ELEMENT: This event means that the parser finishes parsing a specific element in the document.
  • CHARACTERS: This event means that the parser reads the text value of the currently parsed element.

Putting all together, we implement the following class for parsing students.xml and populating List of Student objects:

When executing the above class, we get the following output:

4- Source Code

You can download the source code from this repository: Read-XML

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar