RSS

Tag Archives: stax api

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

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 2 of this tutorial demonstrates how to write XML in Java. In Part 1, we read xml using StaX API.

books2.xml

<?xml version="1.0"?><books>
<type>1</type>
<title>901</title>
<author>0</author>
</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.FileOutputStream;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class BookParser
{

private String bookFile;

public void setFile(String bookFile)
{
this.bookFile = bookFile;
}


private void createNode(XMLEventWriter eventWriter, String name,
String value)
{

try
{
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent end = eventFactory.createDTD("\n");
XMLEvent tab = eventFactory.createDTD("\t");
// Create Start node
StartElement sElement = eventFactory.createStartElement("", "",
name);
eventWriter.add(tab);
eventWriter.add(sElement);
// Create Content
Characters characters = eventFactory.createCharacters(value);
eventWriter.add(characters);
// Create End node
EndElement eElement = eventFactory.createEndElement("", "", name);
eventWriter.add(eElement);
eventWriter.add(end);
} catch (FactoryConfigurationError e)
{

e.printStackTrace();
} catch (XMLStreamException e)
{

e.printStackTrace();
}

}

public void saveBooks() throws Exception
{
// Create a XMLOutputFactory
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
// Create XMLEventWriter
XMLEventWriter eventWriter = outputFactory
.createXMLEventWriter(new FileOutputStream(bookFile));
// Create a EventFactory
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent end = eventFactory.createDTD("\n");
// Create and write Start Tag
StartDocument startDocument = eventFactory.createStartDocument();
eventWriter.add(startDocument);

// Create books open tag
StartElement booksStartElement = eventFactory.createStartElement("","", "books");
eventWriter.add(booksStartElement);
eventWriter.add(end);
// Write the different nodes
createNode(eventWriter, "type", "1");
createNode(eventWriter, "title", "901");
createNode(eventWriter, "author", "0");

eventWriter.add(eventFactory.createEndElement("", "", "books"));
eventWriter.add(end);
eventWriter.add(eventFactory.createEndDocument());
eventWriter.close();
}
}


So now we are going to write XML to books2.xml

public class TestWrite
{

/**
* @param args
*/
public static void main(String[] args)
{
BookParser parser = new BookParser();
parser.setFile("books2.xml");
try
{
parser.saveBooks();
} catch (Exception e)
{
e.printStackTrace();
}

}

}


Advertisements
 
Leave a comment

Posted by on November 5, 2012 in Java, XML

 

Tags: ,

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

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);
}

}

}

 
Leave a comment

Posted by on November 5, 2012 in Java, XML

 

Tags: ,