Monday, November 5, 2012

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

[sourcecode language="xml"]
<?xml version="1.0"?><books>
<type>1</type>
<title>901</title>
<author>0</author>
</books>
[/sourcecode]


Book.java (Model class)

[sourcecode language="java"]
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 + "]";
}

}
[/sourcecode]

BookParser.java

[sourcecode language="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();
}
}


[/sourcecode]


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

[sourcecode language="java"]
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();
}

}

}


[/sourcecode]

No comments:

Post a Comment

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...