AddThis

Bookmark and Share

Wednesday, 4 February 2009

An easy to use XML Serializer

XML processing is an important part in present software systems, especially when communicate with other software components in the IT infrastructure. Pretty often you must provide your object data as XML. The Open Source market provides a wide range of XML tools, above all XML mapping tools, like Castor, JAXB and others. A very intersting and compact tool, existing since 2004 is XStream hosted on Codehaus. XStream is a proved XML serializing library and provides the following key features:
  • Easy to use API (see example)
  • You do not need explicit mapping files, like other serializing tools
  • Good performance
  • Full object graph support
  • You can modify the XML output
Let us consider a simple business object, person, implemented as a POJO (taken from the XStream homepage):

public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
// ... constructors and methods
}

public class PhoneNumber {
private int code;
private String number;
// ... constructors and methods
}
In order to get a XML representation of the Person object we simple use the XStream API. We also set alias names which are used in the output XML.
XStream xstream = new XStream();
xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);
String resultXml = xstream.toXml(myPerson)
When creating a new instance of the person object an serialize it via xstream (toXml) we get the following XML result. As we can see our alias names are used.


Joe
Walnes

123
1234-456


123
9999-999



The example illustrates that the framework is very compact and easy to use. Look at the 2 Minute tutorial on the XStream homepage to get more examples. You can also implement custom converter and transformation strategies to adapt XStream to your requirements.

Have fun with XStream.

0 comments:

Post a Comment