Simple XML-serialization using Simple XML

In my last post I introduced Simple XML as an easy to use XML-Object mapper. I showed how to map XML-files to POJOs.
In this post I’ll deal with the other way round: store POJOs to XML-files. To show you how this is done with Simple XML, I’ll utilize and extend the calculator-example again.
After we have loaded the calculations, we should calculate them and store the results to our new Result-classes:

public class Result {

	private final int result;

	public Result(int result) {
		this.result = result;

public class Results {

	private List results;

	public Results(List results) {
		this.results = results;


There are no new annotations, just POJOs. In order to store the results, I modified the existing Calculation(s)-classes:

public class Calculation {

	private Operator operator;

	private int valueA;

	private int valueB;

	public Result getResult(){
		return new Result(operator.calculate(valueA, valueB));
public class Calculations {

	private List calculations;

	public List calculateAll(){
		List results = new ArrayList();
		for(Calculation c:calculations){
		return results;


What steps do we have to perform now?

  • Read the calculations from calculations.xml
  • Calculate the results
  • Store the results into results.xml

Translated into code, this is what it looks like:

        public static void main(String[] args) throws Exception {

	public static Calculations read() throws Exception{
		Serializer serializer = new Persister();
		File file = new File("calculations.xml");
		return, file);

	public static Results calculate(Calculations calculations){
		return new Results(calculations.calculateAll());

	public static void write(Results results) throws Exception{
		Serializer serializer = new Persister();
		File file = new File("results.xml");
		serializer.write(results, file);

As you can see, serializing to XML is also pretty easy and nothing compared to the common DOM or SAX-frameworks.
Finally, let’s take a look at the written xml-file:

  <results class="java.util.ArrayList">
    <result result="3"/>

This is almost what we expected, except of the new class-attribute in results-element. This attribute is automatically generated by Simple XML to determine the implementation of the java.util.List-interface that was used while the file was serialized (we created a new ArrayList instance in line 8 of Calculations-class). Whenever the file gets deserialized an instance of this class will be used to store the results (defaults to java.util.ArrayList).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s