Java Articles

Advertisement

JAXP StAX Stream Reader Example

by Ram Satish

Share

StAX also provides a streaming, event-driven push based parser. In order to understand StAX model, we first need to know a bit about the document object model (DOM) and Simple API for XML model (SAX).

In DOM, the entire XML’s object model is ready into the memory so it allows one to navigate through the document tree and manipulate it as necessary.

Unlike DOM, SAX APIs are streaming based where the parser reads the XML, invokes the callback methods as it encounters  start and end of elements and character data. Since the parser drives the reading of XML and invokes the callback methods, SAX can be called as an event-driven, streaming, push parser.

StAX offers a simpler programming model than SAX and more efficient memory management than DOM. Like SAX, StAX is streaming and event-driven but unlike SAX, StAX APIs are based on push-parsing API where the streaming is controlled by the XML parser rather than the client. Since client drives the streaming, multiple documents can be parsed.In this article, we will see an example of StAX stream reader.

StAX Stream Reader API

Advertisement

Create a new instance of the factory that creates streams.

XMLInputFactory factory = XMLInputFactory.newInstance();

Create the stream reader XMLStreamReader using the factory method createXMLStreamReader(). We will pass the input source of the XML to be parsed.
Once we have the XMLStreamReader object, we will use it to read the XML.

XMLStreamReader reader = factory
.createXMLStreamReader(StAXStreamReaderExample.class
.getResourceAsStream("sample.xml"));

XMLStreamReader.hasNext() let’s us know whether there is any parse event.
We will use XMLStreamReader.next() to make the reader read the next parse event. It returns an integer value which we will use to identify the type of event parsed.
The next() method returns an integer which identifies the type of event just read.
The event type can be defined as:

  1. An XML declaration
  2. A DTD
  3. Start tag
  4. Character data
  5. White space
  6. End tag
  7. Comment
  8. or a processing instruction

In the below code we iterate over XML using hasNext() and next() and then look for the start element event.

        while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamConstants.START_ELEMENT:
....
}
}

Once we have read the next parse event, we can access the data by calling method on XMLStreamReader.

  1. getEventType() – event type
  2. getNamespaceURI() – namespace URI
  3. getLocalName() – local tag name
  4. getText() – tag content

Example of StAX Stream Reader

Here is the complete example. sample.xml that contains employee details in XML form. We will parse it using StAX stream reader and convert the XML into employee beans.

sample.xml

<?xml version="1.0"?>
<employees>
<employee id="1">
<name>Joe</name>
<age>34</age>
</employee>
<employee id="2">
<name>Sam</name>
<age>24</age>
</employee>
<employee id="3">
<name>John</name>
<age>44</age>
</employee>
</employees>

Employee:

package com.javarticles.jaxp;

public class Employee {
private String name;
private Integer age;
private Integer id;

Employee(){}

Employee(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String toString() {
return "Employee(id:"+ id + ", name:" + name + ", age:" + age + ")";
}
}

StAXStreamReaderExample:

package com.javarticles.jaxp;

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

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class StAXStreamReaderExample {
public static void main(String[] args) throws XMLStreamException {
List empList = null;
Employee currEmp = null;
String tagContent = null;
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory
.createXMLStreamReader(StAXStreamReaderExample.class
.getResourceAsStream("sample.xml"));
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamConstants.START_ELEMENT:
if ("employee".equals(reader.getLocalName())) {
currEmp = new Employee();
currEmp.setId(Integer.parseInt(reader.getAttributeValue(0)));
}
if ("employees".equals(reader.getLocalName())) {
empList = new ArrayList<>();
}
break;

case XMLStreamConstants.CHARACTERS:
tagContent = reader.getText().trim();
break;

case XMLStreamConstants.END_ELEMENT:
switch (reader.getLocalName()) {
case "employee":
empList.add(currEmp);
break;
case "name":
currEmp.setName(tagContent);
break;
case "age":
currEmp.setAge(Integer.parseInt(tagContent));
break;
}
break;

case XMLStreamConstants.START_DOCUMENT:
empList = new ArrayList<>();
break;
}
}
empList.stream().forEach(System.out::println);
}
}

Output:

Employee(id:1, name:Joe, age:34)
Employee(id:2, name:Sam, age:24)
Employee(id:3, name:John, age:44)

Download the source code

This was an example about StAX Stream Reader.

You can download the source code here: jaxpStaxStreamReaderExample.zip

Share

Advertisement

Related

Advertisement

Latest

Advertisement