Out of the box, XStream is able to serialize most objects without the need for custom mappings to be setup. The XML produced is clean, however sometimes it's desirable to make tweaks to it. The most common use for this is when using XStream to read configuration files and some more human-friendly XML is needed.
The simplest and most commonly used tweak in XStream is to alias a fully qualified class to a shorter name.
Given the following class:
package com.something.animals; public class Cat { public Cat(int age, String name) { this.age = age; this.name = name; } int age; String name; }
XStream can be used to serialize and deserialize an instance of this to XML:
XStream xstream = new XStream(); String xml = xstream.toXml(new Cat(4, "Garfield")); // serialize Cat cat = (Cat)xstream.fromXml(xml); // deserialize
The XML representation, looks like this:
<com.something.animals.Cat> <age>4</age> <name>Garfield</name> </com.something.animals.Cat>
To shorten the fully qualified class name in the XML, an alias can be defined:
XStream xstream = new XStream(); xstream.alias("cat", Cat.class); String xml = xstream.toXml(new Cat(4, "Garfield")); // serialize Cat cat = (Cat)xstream.fromXml(xml); // deserialize
The result:
<cat> <age>4</age> <name>Garfield</name> </cat>