Monday, August 11, 2008

XStream : The simple XML Parser

XStream is an xml parsing API implemented in Java. Key things about XStream is that it is very simple, lightweight, easy-to-use and open-source.

Let me show you how to start off with XStream.

Download XStream jar file, and have it in your classpath.

Let's see how to serialize an object into xml using XStream.

We have a class 'Person'
public class Person {
private String name = "";
private String address = "";

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}
Here's how we serialize an Object of Class 'Person'


public void writeAsXml() {

Person person = new Person();
person.setName("Bob");
person.setAddress("Georgia");

XStream xStream = new XStream();
try {
FileOutputStream fs = new FileOutputStream("/tmp/person.xml");
xStream.toXML(person, fs);
} catch (FileNotFoundException fe) {
fe.printStackTrace();
}

}


The xml output we get looks like this:
<Person>
<name>Bob</name>
<address>Georgia</address>
</Person>

Easy, huh?

Now going on to deserialze Objects from XML,

public void readFromXml() {

XStream xStream = new XStream(new DomDriver());

try {
FileInputStream fin = new FileInputStream("/tmp/person.xml");
Person person = (Person) xStream.fromXML(fin, new Person());
System.out.println("Hello "+person.name+", from "+person.address);
} catch (FileNotFoundException fe) {
fe.printStackTrace();
}

}

We can accomplish more complicated stuff using XStream. But for a start I guess this is enough :)

No comments:

Post a Comment

Bookmark

AddThis Social Bookmark Button