XStream – Java to XML Using Annotation

Convert Java to XML using annotation

In the previous tutorials we saw an example of how to create a java object from XML. That tutorial also explained the concept of aliases and implicit collection. In this tutorial we continue with that but use annotation on the java class. The advantage with annotation is that it is faster to code and develop. the disadvantage is that you bind the java class to XStream.

In the example below we convert an object of type JazzArtist to XML. JazzArtist contains fields name, isAlive, a url and a list of albums. This example uses the following annotations

  • @XStreamAlias – Used on the type, field or attribute. To understand ‘aliases’ look at this tutorial
  • @XStreamImplicit – Used on Collections or array. To understand ‘Implicit Collections/Arrays’ look at the this tutorial.
  • @XStreamAsAttribute – Used to mark a field as an attribute.
  • @XStreamConverter – Use a specific converter for this field. We will look at Converters in detail in a later tutorial. In this example we use a Boolean converter for ‘isAlive’ field, we want the XML to have values yes or no instead of true or false.

Here is the complete example. In this example we want to create an XML from an object of type JazzArtist2.

  • We use annotation to first use an alias of ‘artist’ for JazzArtist2. Each Jazz Artist has a list of albums.
  • In the resulting XML we dont want the albums to appear under the element ‘albums’, rather we want each album to be the child of the artist element. We therefore mark ‘albums’ as an implicit collection using the @XStreamImplicit annotation.
  • We don’t want to include the ‘noOfRecords’ in the resulting XML, we therefore use the @XStreamOmitField to omit that field.
  • We want genre to be an attribute of the album instead of a child. we use @XStreamAsAttribute to mark genre as an attribute.
  • In this example we also use an annotation for a Converter. There is a boolean field in the JazzArtist2 class called isAlive. We dont want the XML to have values ‘true’ or ‘false’ but values ‘yes’ or ‘no’ since they are more human friendly. The @XStreamConverter can be used to specify a Converter and pass values to its constructor.

The resulting XML

Leave a Reply

Your email address will not be published. Required fields are marked *