Five Minute Tutorial

Version 4 by Robin Shen
on Feb 10, 2010 04:26.


compared with
Version 5 by Robin Shen
on Feb 10, 2010 05:23.


Key
These lines were removed. This word was removed.
These lines were added. This word was added.

View page history


There are 5 changes. View first change.

 We demonstrate usage of this tool with a simple tutorial. Assume a _Task_ class below with a _prioritized_ field indicating whether it is a prioritized task:
 {code}
 package example;
  
 public class Task {
  public boolean prioritized;
 }
 {code}
 With XStream, we can serialize object of this class to XML like below:
 {code}
 import com.thoughtworks.xstream.XStream;
  
 Task task = new Task();
task.setPrioritized(true);
  task.prioritized = true;
 String xml = new XStream().toXML(task);
 saveXmlToFileOrDatabase(xml);
 {code}
Resulting XML will be:
  The resulting XML will be:
 {code}
 <example.Task>
  <prioritized>true</prioritized>
 </example.Task>
 {code}
 And you can deserialize the XML to get back task object:
 {code}
import com.thoughtworks.xstream.XStream;
 import com.thoughtworks.xstream.io.xml.DomDriver;
  
 String xml = readXmlFromFileOrDatabase();
 Task task = (Task)(new XStream(new DomDriver()).fromXML(xml));
 {code}
 Everything is fine. Now we find a prioritized flag is not enough, so we enhance the Task class to use a numeric priority field ranging from 1 to 10:
 {code}
 package example;
  
 public class Task {
  public int priority;
 }
 {code}
 However deserialization of previously saved xml is no longer possible since the new Task class is not compatible with previous version.
  However deserialization of previously saved xml is no longer possible since the new Task class is not compatible with previous version. XMT comes to rescue: it introduces class _VersionedDocument_ to version serialized XMLs and handles the migration. With XMT, serialization of task object can be written as:
 {code}
 package example;
 import com.pmease.commons.xmt.VersionedDocument;
  
 Task task = new Task();
 task.prioritized = true;
 String xml = VersionedDocument.fromBean(task).toXML();
 saveXmlToFileOrDatabase(xml);
 {code}
 The resulting XML will be:
 {code}
 <?xml version="1.0" encoding="UTF-8"?>
  
 <example.Task version="0">
  <prioritized>true</prioritized>
 </example.Task>
 {code}
 Compared with the XML generated by directly using XStream, an additional attribute _version_ is added to the root element indicating version of the class generating this XML. The value is set to _0_ unless there are migration methods defined in the class as we will introduce below.
  
 The XMT version of deserializing task object from xml is:
 {code}
  
 {code}