Revisions on July 23, 2008: Under Serializing objects, added the Using Aliases sidebar.
Using XStream, you can serialize most Java objects without any mapping. Object names become element names in the XML produced, and the strings within classes form the element content of the XML. The classes that you serialize with XStream don't need to implement the Serializable interface. XStream is a serialization tool and not a data binding tool, which means that it doesn't perform class generation from an XML or XML Schema Definition (XSD) file.
Three features distinguish XStream from any other serializing tool:
- XStream doesn't care about the visibility of the fields of the class being serialized/deserialized.
- No getter and setter methods are required for the fields of the class to be serialized/deserialized.
- The class being serialized/deserialized is not required to have a default constructor.
You can directly serialize and deserialize any third-party class using XStream without making any changes to the class.
Setting up the development environment
Follow these steps to download and install XStream (see Resources for download links):
- Download Eclipse from the Eclipse Web site. To install, unpack it to any folder of your choice, which I'll refer to as eclipse_home in this article. This article assumes Eclipse version 3.3.
- Download the latest stable version of XStream from the XStream Web site. To install, unpack it to any folder of your choice, which I'll refer to as xstream_home. This article assumes XStream version 1.2.2.
- Download the Java Platform, Standard Edition (J2SE) software development kit (SDK) from the Sun Web site. Install it in any folder of your choice, which I'll refer to as java_home. This article assumes version 1.5.0_05.
To create a Java project, go to File > New > Project, then follow these steps:
- Go to Java > Java Project > Next (see Figure 1).
Figure 1. Beginning a new Java project
- Fill in the project name and click Next (see Figure 2).
Figure 2. Filling in the project name
- Click Finish to complete the task (see Figure 3).
Figure 3. Finalizing the setup
Figure 4 shows the result of creating a Java project.
Figure 4. A new Java project

Follow these steps to add the XStream libraries to the project you just created:
- With the project selected in Project Explorer in Eclipse, go to the Project menu and choose Properties (see Figure 5).
Figure 5. Adding XStream libraries
- Click Add External JARs, and select xstream-1.2.2.jar from the xstream_home/lib folder.
- Click OK to complete the task (see Figure 6).
Figure 6. Finalizing XStream support
Figure 7 shows the result of adding XStream support to the project.
Figure 7. The added libraries

This simple example, which demonstrates how you can serialize/deserialize objects using XStream, features two classes: Writer and Reader. The Writer class uses the XStream API to serialize an object of type Employee into XML and store it in a file in the file system (see Listing 1).
Listing 1. Writer.java
package com.samples;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.thoughtworks.xstream.*;
public class Writer {
public static void main(String[] args) {
Employee e = new Employee();
//Set the properties using the setter methods
//Note: This can also be done with a constructor.
//Since we want to show that XStream can serialize
//even without a constructor, this approach is used.
e.setName("Jack");
e.setDesignation("Manager");
e.setDepartment("Finance");
//Serialize the object
XStream xs = new XStream();
//Write to a file in the file system
try {
FileOutputStream fs = new FileOutputStream("c:/temp/employeedata.txt");
xs.toXML(e, fs);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
|
The Reader class reads this file, deserializes the XML, and gets the data into a Java object (see Listing 2).
Listing 2. Reader.java
package com.samples;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class Reader {
public static void main(String[] args) {
XStream xs = new XStream(new DomDriver());
Employee e = new Employee();
try {
FileInputStream fis = new FileInputStream("c:/temp/employeedata.txt");
xs.fromXML(fis, e);
//print the data from the object that has been read
System.out.println(e.toString());
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
|
Listing 3 shows the structure of the Employee object.
Listing 3. Employee.java
package com.samples;
public class Employee {
private String name;
private String designation;
private String department;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
@Override
public String toString() {
return "Name : "+this.name+
"\nDesignation : "+this.designation+
"\nDepartment : "+this.department;
}
}
|
Most applications depend on a number of properties. These properties can be the name of a data source to connect to or the location of a log file. A configuration file is the best place to store this data, because it ensures that you can change these properties without recompiling the application, and it makes maintaining the application easier. This example scenario illustrates how you can use XStream in an application to read the configuration properties from an XML configuration file.
Typical XML data binding requires you to generate a Java object from an XML file. With XStream, there is no object-generation phase. You simply write a Java class and map the fields of the class to the elements of the XML that you wish to read. This example assumes the configuration file shown in Listing 4.
Listing 4. Config.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<datasource-name>IRIS</datasource-name>
<ipaddress>9.124.74.85</ipaddress>
<logfilename>DailyLogApplication.log</logfilename>
<appender>console</appender>
</config>
|
Listing 5 shows the code for the ConfigReader class, which reads the configuration file and loads the properties into a Java object.
Listing 5. ConfigReader.java
package com.samples;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class ConfigReader {
String datasourcename = null;
String ipaddress = null;
String logfilename = null;
String appender = null;
@Override
public String toString() {
// This method prints out the values stored in the member variables
return "Datasource Name : "+datasourcename+
" \nIP Address : "+ipaddress+
" \nLogfilename : "+logfilename+
" \nAppender : "+appender;
}
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
XStream xs = new XStream(new DomDriver());
FileInputStream fis = new FileInputStream("c:/temp/Config.xml");
xs.aliasField("datasource-name", ConfigReader.class, "datasourcename");
xs.alias("config", ConfigReader.class);
ConfigReader r = (ConfigReader)xs.fromXML(fis);
System.out.println(r.toString());
}
}
|
To set up and develop an application with XStream is a simple matter of a few easy steps. Now that you know how to use XStream to serialize and deserialize Java objects and read configuration files, you can learn more about aliases, annotations, and converters at the XStream site (see Resources for tutorial links). Aliases and converters enable you to have complete control over the XML that is generated.
| Description | Name | Size | Download method |
|---|---|---|---|
| Java source code from this article | x-xstreamcode.zip | 3KB | HTTP |
Information about download methods
Learn
- The Two Minute Tutorial: A good place to
start is this very quick intro to XStream. Skim read it to get an idea of how simple it is to convert objects to XML and back again.
- XStream's Tweaking the Output
page: Find additional information about how to tweak output from XStream.
- The Converter Tutorial: For you advanced users, gain complete control over the XML that is generated/read.
- Refer to Practical data binding: Get your feet wet in the real world (Brett McLaughlin, developerWorks, May 2004): Find out more about data binding.
- XML and Java
technologies: Data Binding, Part 1: Code generation approaches—JAXB and more
(Dennis Sosnoski, developerWorks, January 2003): Also, look at several more approaches to XML data binding.
- New to XML page: Check out the XML zone's updated resource central for XML.
- IBM XML certification: Find out how you can become an IBM-Certified Developer in XML and related technologies.
- XML technical library: See the developerWorks XML Zone for a wide range of technical articles and tips, tutorials, standards, and IBM Redbooks.
- developerWorks technical events and webcasts: Stay current with technology in these sessions.
- The technology
bookstore: Browse for books on these and other technical topics.
- Podcasts: Tune in and catch up with IBM technical experts.
Get products and technologies
- Eclipse: Download and install Eclipse from the Eclipse Web site.
- Download
XStream: From the XStream
Web site, download this simple library to serialize objects to XML and back again.
- IBM trial software: Build your next development project with trial software available for download directly from developerWorks.
Discuss
- XML zone discussion forums: Participate in any of several XML-related discussions.
- developerWorks XML zone: Share your thoughts: After you read this article, post your comments and thoughts in this forum. The XML zone editors moderate the forum and welcome your input.
- developerWorks blogs: Check out these blogs and get involved in the developerWorks community.

Rajiv Bangalore is a Senior Staff Software Engineer with IBM India. He has been involved in various Java Platform, Enterprise Edition (Java EE) development projects in his career spanning seven years. Contact him at rajiv.bangalore@in.ibm.com.





