XStream is a library to serialize objects to XML and vice versa. It must not be used as a XML processor.

The way that XStream serializes and de-serializes objects is by using Annotations. This post will show you how to annotate a class and how to serialize it.

First of all let’s introduce the class:

public class Book { private String isbn; private List author; private String title; private int pages; //class continues... }

This class models a book. It has the ISBN, a list of authors (it’s only a String per author), the title and the number of pages. The point of XStream is that it uses reflection to serialize and de-serialize the objects.
We want to serialize this book to this XML:

<BOOK> <ISBN>978-0-9815316-0-1</ISBN> <AUTHOR>Martin Odersky</AUTHOR> <AUTHOR>Lex Spoon</AUTHOR> <AUTHOR>Bill Venners</AUTHOR> <TITLE>Programming in Scala</TITLE> <PAGES>736</PAGES> </BOOK>

The next step is to annotate the class:

package com.wordpress.j2eethoughts; import com.thoughtworks.xstream.annotations.XStreamAlias; import java.util.List; @XStreamAlias("BOOK") public class Book { @XStreamAlias("ISBN") private String isbn; //no annotations private List author; @XStreamAlias("TITLE") private String title; @XStreamAlias("PAGES") private int pages; //class continues... }

Note that lists must not be annotated. After this, we need to create the facade of XStream:

package com.wordpress.j2eethoughts; import java.util.ArrayList; import java.util.List; import com.thoughtworks.xstream.XStream; public class Main { public static void main(String[] args) { XStream xs = new XStream(); xs.processAnnotations(Book.class); xs.addImplicitCollection(Book.class, "authors", "AUTHOR", String.class); List authors = new ArrayList(); authors.add("Martin Odersky"); authors.add("Lex Spoon"); authors.add("Bill Venners"); Book book = new Book("978-0-9815316-0-1", authors,"Programming in Scala", 736); System.out.println(xs.toXML(book)); } }

And that’s all, now you can serialize any Book object. For de-serialization you must call the method xs.fromXML passing a String to the method.