How to Serialize Objects to XML and Back Again with XStream?

Google+ Facebook Twitter LinkedIn Dzone Reddit Digg Blogger Hacker News Addthis

By Markus Sprunck; Revision: 1.2; Status: final; Last Content Change: Feb 4, 2013;  

To create XML from Java objects is something that can be very error prone, e.g. doing the correct encoding of the various data types can be tricky. This is the reason why you never should do this by your own in Java. One of my favorite library to convert objects from and to XML is XStream. The following code sample describes some basic features.

How to Serialize Objects to XML and Back Again with XStream?

The XStream implementation is simple, straightforward and has a small footprint. The following sample code is based on the current version 1.4.2 released in November 2011. 

It creates an instance of a class, serializes the object to XML and back again to a new object. To run the sample you need three libraries in the build path (i) xstream-1.4.2.jar, (ii) xmlpull- and (iii) xpp3_min-1.1.4c.jar. 

// File #1: 

The output of the application should be something like this:


Change History

 Revision  Date  Author  Description
 1.0  Jul 10, 2012  Markus Sprunck   first version
 1.1  Aug 18, 2012  Markus Sprunck  improved layout for tablets
 1.2  Feb 4, 2013   Markus Sprunck  improvements

Google+ Comments

You may press the +1 button to share and/or comment