Java StAX Parser Example to read XML file

Filed Under: Java

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, stax parser example, java stax parser example read xml file
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.


<?xml version="1.0" encoding="UTF-8"?>
	<Employee id="1">
		<role>Java Developer</role>
	<Employee id="2">

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

package com.journaldev.xml;

public class Employee {
    private int id;
    private String name;
    private String gender;
    private int age;
    private String role;
    public int getId() {
        return id;
    public void setId(int id) { = id;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public String getGender() {
        return gender;
    public void setGender(String gender) {
        this.gender = gender;
    public int getAge() {
        return age;
    public void setAge(int age) {
        this.age = age;
    public String getRole() {
        return role;
    public void setRole(String role) {
        this.role = role;
    public String toString() {
        return "Employee:: ID="" Name=" + + " Age=" + this.age + " Gender=" + this.gender +
                " Role=" + this.role;

Java StAX Parser Example to read XML file

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

package com.journaldev.xml;

import java.util.ArrayList;
import java.util.List;

import javax.xml.namespace.QName;

public class StaxXMLReader {

    public static void main(String[] args) {
        String fileName = "/Users/pankaj/employee.xml";
        List<Employee> empList = parseXML(fileName);
        for(Employee emp : empList){

    private static List<Employee> parseXML(String fileName) {
        List<Employee> empList = new ArrayList<>();
        Employee emp = null;
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        try {
            XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileInputStream(fileName));
                XMLEvent xmlEvent = xmlEventReader.nextEvent();
               if (xmlEvent.isStartElement()){
                   StartElement startElement = xmlEvent.asStartElement();
                       emp = new Employee();
                       //Get the 'id' attribute from Employee element
                       Attribute idAttr = startElement.getAttributeByName(new QName("id"));
                       if(idAttr != null){
                   //set the other varibles from xml elements
                   else if(startElement.getName().getLocalPart().equals("age")){
                       xmlEvent = xmlEventReader.nextEvent();
                   }else if(startElement.getName().getLocalPart().equals("name")){
                       xmlEvent = xmlEventReader.nextEvent();
                   }else if(startElement.getName().getLocalPart().equals("gender")){
                       xmlEvent = xmlEventReader.nextEvent();
                   }else if(startElement.getName().getLocalPart().equals("role")){
                       xmlEvent = xmlEventReader.nextEvent();
               //if Employee end element is reached, add employee object to list
                   EndElement endElement = xmlEvent.asEndElement();
        } catch (FileNotFoundException | XMLStreamException e) {
        return empList;


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

Employee:: ID=1 Name=Pankaj Age=29 Gender=Male Role=Java Developer
Employee:: ID=2 Name=Lisa Age=35 Gender=Female Role=Manager

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


  1. Arunselvan says:

    hello this is very usefull one. It works well for me. But if we dont have the attribute. Then at that time how can we retrieve the values for tag. For me there is no attributes. In that case i cant able to retrieve the values inside the xml tag.

  2. Sahil Sethi says:

    The above code doesn’t seem to work if any of the elements is empty. For eg if field is empty. How can we resolve this issue ??

    1. Sahil Sethi says:

      EDIT: For eg if the AGE field is empty.

      1. Vijay Deshmukh says:

        if the age field is empty then its up to you if you want to save any default value or wish to have it blank i.e. null, if it is mandatory from user’s end then trow an exception and come out of the program itself with appropriate message.

        1. Vijay Deshmukh says:

          I removed age from second employee node and it is setting it to 0 for me.

  3. Javix says:

    Any of your else if clause can produce a NPE because an Employee instance is initialized only in the ‘if’ block.

  4. Jim says:

    This is a very helpful example. I can see, though, where creating the bean classes can get to be a time-consuming burden in situations where dozens of different xml file types that translate to objects are being handled. It seems that there’s much to be gained from automating this part of the process – having a code generator, if you will, that walks through each xml file it finds and automatically builds the bean class for us. Can you suggest an example of this?

    Ideally this code generator would also structure the StAX reader class based on the bean structure gleaned from the actual xml file itself, too. But I need to walk before I run, and don’t want to seem all too greedy . Thanks in advance for any insights or suggestions.

  5. Nikhil Kanojia says:

    Thanks man,it really worked fine for me…send me your email id if possible, i would like to ask few more questions.Thanks a lot.

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages