Wednesday, 23rd June 2010
The new frontier for learning Java

Serialize to XML using XStream

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book

In this article I'll show you how to create automatically an XML text containing the serialized version of any Object.

Contents

The Article

Image:250px-Subversion.png
You can download the complete code of this article from the Subversion repository at this link

Using the username:readonly and password: readonly

See the using the SVN repository instructions page for more help about this.

With Xstream serializing to XML or to Json mostly the same steps are required. In this article I'll explain things quickly, demanding you to read the article: Serialize to json with Xstream, which contains more detailed explanations.

Creating the XML from the Object

By default the com.thoughtworks.xstream.XStream Class is initialized using the XPP3 Driver, which is a very fast implementation of the XML API. To run this example you need to include in your class path the xpp3_min-1.1.4c.jar library.

If you don't want you can use the XML API inbuilt in the JDK and initialize the XStream object with:

XStream xstream = new XStream(new DomDriver());

It will be a bit slower during execution, but you won't need the xpp3 library.

Once the creation of the object is settled you can continue creating your XML String in the same way you would do with the JSON. So for detail about how the following code works look at the article: Serialize to json with Xstream.

// this requires the XPP3 Library
	XStream xstream = new XStream();
 
	// optional to make the output more concise
	xstream.alias("person", Person.class);
	xstream.alias("address", Address.class);
 
	// serializes the Person to XML
	String xml = xstream.toXML(person);


Creating the Object from the XML

The deserialization is pretty straight forward too, look at the article Serialize to json with Xstream for details about how it works.

	Person newPerson = (Person) xstream.fromXML(xml);


Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Title (required):

Website:

Comment: