RSS

StaX API – The XML Parser for Java (Part 1)

05 Nov

There are differnet methods to parse XML in Java. Dom(Document Object Model) and SAX(Simple API for XML) are well known APIs. However this tutorial uses StaX API(Streaming API for XML) which is more sophisticated than others.

The core StaX API comes in two flavors to parse XML. They are

  •     Cursor API
  •     Event Iterator API

Event Iterator API is more flexible than Cursor API. So let’s focus on Event Iterator API. Part 1 of this tutorial demonstrates how to read XML in Java. Part2 of this tutorial is about writing XML.

books.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
<book isbn="000-1">
<type>novel</type>
<title>Kidnaped</title>
<author>R.L.Stevenson</author>
</book>
<book isbn="000-2">
<type>religious</type>
<title>Peace of mind</title>
<author>N.K.Dumney</author>
</book>
<book isbn="000-3">
<type>educational</type>
<title>Head First Java</title>
<author>Kathy Sierra</author>
</book>
</books>

Book.java (Model class)

package model;

public class Book {

private String isbn;
private String type;
private String title;
private String author;

public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}

@Override
public String toString() {
return "Book [isbn=" + isbn + ", type=" + type + ", title=" + title
+ ", author=" + author + "]";
}

}

BookParser.java


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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;

import model.Book;

public class BookParser
{
static final String BOOK = "book";
static final String ISBN = "isbn";
static final String TYPE = "type";
static final String TITLE = "title";
static final String AUTHOR = "author";

@SuppressWarnings("unchecked")
public List<Book> readBooks(String file)
{
List<Book> books = new ArrayList<Book>();
try
{
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
InputStream in = new FileInputStream(file);
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
Book book = null;

while (eventReader.hasNext())
{
XMLEvent event = eventReader.nextEvent();

if (event.isStartElement())
{
StartElement startElement = event.asStartElement();
if (startElement.getName().getLocalPart() == (BOOK))
{
book = new Book();
// Read attributes of Book element
Iterator<Attribute> attributes = startElement
.getAttributes();
while (attributes.hasNext())
{
Attribute attribute = attributes.next();
if (attribute.getName().toString().equals(ISBN))
{
book.setIsbn(attribute.getValue());
}
}
}

if (event.isStartElement())
{
if (event.asStartElement().getName().getLocalPart()
.equals(TYPE))
{
event = eventReader.nextEvent();
book.setType(event.asCharacters().getData());
continue;
}
}

if (event.asStartElement().getName().getLocalPart()
.equals(TITLE))
{
event = eventReader.nextEvent();
book.setTitle(event.asCharacters().getData());
continue;
}
if (event.asStartElement().getName().getLocalPart()
.equals(AUTHOR))
{
event = eventReader.nextEvent();
book.setAuthor(event.asCharacters().getData());
continue;
}
}
// Reach the end of book element
if (event.isEndElement())
{
EndElement endElement = event.asEndElement();
if (endElement.getName().getLocalPart() == (BOOK))
{
books.add(book);
}
}
}

} catch (FileNotFoundException ex)
{
ex.printStackTrace();
} catch (XMLStreamException ex)
{
ex.printStackTrace();
}
return books;
}

}

So now we are going to read XML from books.xml


import java.util.List;

import model.Book;

public class TestRead
{

/**
* @param args
*/
public static void main(String[] args)
{
BookParser parser = new BookParser();
List<Book> books = parser.readBooks("books.xml");
for (Book book : books)
{
System.out.println(book);
}

}

}

Advertisements
 
Leave a comment

Posted by on November 5, 2012 in Java, XML

 

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: