Monday, March 18, 2013

XML serialization and de-serialization in Java

It is sometimes a great issue when one wants to serialize their objects into XML files. We have JAXB(Java Architecture for XML Binding) API which can serialize and also de-serialize the java object. I will introduce frequently used annotation used for XML serialization with example:

1. Annotating XML variables

@XmlRootElement(namespace="className" or name="className")
@XmlType(propOrder={"property", "list"})
public class className{
   private int attribute;
   private String property;
   private String value;
   private List list;

  public int getAttribute(){
   return this.attribute;

  public String getProperty(){
   public String getValue(){
   return this.value;

public List getList(){
  return this.list;

We can define the annotations for extended objects as follows:

public baseClassObject getObject(){
       return this.object;

2. Serializing Object

JAXBContext context = JAXBContext.newInstance(className.class);
Marshaller m = context.createMarshaller();
//Format the output
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(classNameObject, fileObject); 
// or to just print to the console
m.marshal(classNameObject, System.out);

3. DeSerialising Object

JAXBContext context = JAXBContext.newInstance(className.class);
Unmarshaller m = context.createUnmarshaller();
classNameObject = (className)m.unmarshal(fileObject);

1 comment: