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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="UTF-8"?> <Employees> <Employee id="1"> <age>29</age> <name>Pankaj</name> <gender>Male</gender> <role>Java Developer</role> </Employee> <Employee id="2"> <age>35</age> <name>Lisa</name> <gender>Female</gender> <role>Manager</role> </Employee> </Employees> |
To read this XML into Employees list, we will create Employee bean first.
Employee.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
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) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.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; } @Override public String toString() { return "Employee:: ID="+this.id+" Name=" + this.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.
StaxXMLReader.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
package com.journaldev.xml; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class StaxXMLReader { public static void main(String[] args) { String fileName = "/Users/pankaj/employee.xml"; List<Employee> empList = parseXML(fileName); for(Employee emp : empList){ System.out.println(emp.toString()); } } 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)); while(xmlEventReader.hasNext()){ XMLEvent xmlEvent = xmlEventReader.nextEvent(); if (xmlEvent.isStartElement()){ StartElement startElement = xmlEvent.asStartElement(); if(startElement.getName().getLocalPart().equals("Employee")){ emp = new Employee(); //Get the 'id' attribute from Employee element Attribute idAttr = startElement.getAttributeByName(new QName("id")); if(idAttr != null){ emp.setId(Integer.parseInt(idAttr.getValue())); } } //set the other varibles from xml elements else if(startElement.getName().getLocalPart().equals("age")){ xmlEvent = xmlEventReader.nextEvent(); emp.setAge(Integer.parseInt(xmlEvent.asCharacters().getData())); }else if(startElement.getName().getLocalPart().equals("name")){ xmlEvent = xmlEventReader.nextEvent(); emp.setName(xmlEvent.asCharacters().getData()); }else if(startElement.getName().getLocalPart().equals("gender")){ xmlEvent = xmlEventReader.nextEvent(); emp.setGender(xmlEvent.asCharacters().getData()); }else if(startElement.getName().getLocalPart().equals("role")){ xmlEvent = xmlEventReader.nextEvent(); emp.setRole(xmlEvent.asCharacters().getData()); } } //if Employee end element is reached, add employee object to list if(xmlEvent.isEndElement()){ EndElement endElement = xmlEvent.asEndElement(); if(endElement.getName().getLocalPart().equals("Employee")){ empList.add(emp); } } } } catch (FileNotFoundException | XMLStreamException e) { e.printStackTrace(); } return empList; } } |
When we execute above program, we get following output in console.
1 2 3 4 |
<span style="color: #008000;"><strong><code> Employee:: ID=1 Name=Pankaj Age=29 Gender=Male Role=Java Developer Employee:: ID=2 Name=Lisa Age=35 Gender=Female Role=Manager </code></strong></span> |
That’s all for a quick Java StAX parser example to read XML file.