Marshalling And Unmarshalling with JAXB

The process of converting Java object into XML is called as marshalling and the reverse is called as unmarshalling. JAXB (Java Architecture for XML Binding) is a specific Java API (the stuff under javax.xml.bind) that uses annotations to bind XML documents to a Java Object Model.

It provides the capability of mapping Java classes to XML representations, and simplifies access to an XML document in a Java program.

JAXB provides two main features:

  • The ability to marshal Java objects into XML
  • The ability to unmarshal XML back into Java objects.

JAXB Dependency:

  • For JDK 1.6 or above, no extra JAXB libraries are required.
  • For JDK < 1.6, download “jaxb-api.jar” and “jaxb-impl.jar”.

Marshalling

The example below demonstrates marshalling of java object to xml document.

We start by creating a POJO, which we would be marshalling into an xml.

@XmlType(propOrder={"name","email","mobileNo","joiningDate"})
@XmlRootElement(name="Employee")
public class Employee {

    private int id;
	
    private String name;
	
    private String email;
	
    private String mobileNo;
	
    private String joiningDate;

    @XmlAttribute(name="id")
    public int getId() {
  	return id;
    }

    public void setId(int id) {
	this.id = id;
    }

    @XmlElement(name="name", required=true)
    public String getName() {
	return name;
    }

    public void setName(String name) {
	this.name = name;
    }

    @XmlElement(name="email", required=true)
    public String getEmail() {
 	return email;
    }

    public void setEmail(String email) {
	this.email = email;
    }

    @XmlElement(name="mobile")
    public String getMobileNo() {
	return mobileNo;
    }

    public void setMobileNo(String mobileNo) {
	this.mobileNo = mobileNo;
    }

    @XmlElement(name="joiningDate")
    public String getJoiningDate() {
	return joiningDate;
    }

    public void setJoiningDate(String joiningDate) {
	this.joiningDate = joiningDate;
    }
}

The Employee class above is a simple POJO other than some JAXB annotations.

  • @XmlType(propOrder={"name","email","mobileNo","joiningDate"}) defines the order in which the elements should appear in the marshalled xml. It is optional.
  • @XmlRootElement defines the root element of the xml.
  • @XmlAttribute defines an xml attribute.
  • @XmlElement defines an xml element.

Now that the POJO is in place, we create JAXBExecutor shown below:

public class JAXBExecutor {
    public static void main(String args[]) throws JAXBException{
		
        File xml = new File("employee.xml");
	Employee emp = new Employee();
	emp.setId(1);
	emp.setName("Ashutosh");
	emp.setEmail("[email protected]");
	emp.setMobileNo("9999999999");
	emp.setJoiningDate("10-12-2010");
		
	JAXBContext contx = JAXBContext.newInstance(Employee.class);
	Marshaller marshaller = contx.createMarshaller();
	marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );  //Pretty Print the xml

	marshaller.marshal(emp, xml);
    }
}

Below are the steps followed for marshalling employee object to employee.xml:

  • We create an instance of our Employee POJO and populate its values.
  • We create an instance of JAXBContext by passing our Employee class.
  • We create the Marshaller object. We also set the JAXB_FORMATTED_OUTPUT as true (optional), which would pretty print the output.
  • We call the marshal() method of the marshaller to marshal the employee object to employee.xml. The marshal() method takes the object to be marshalled and the file to write the output to.

The employee.xml produced by marshalling the employee object is shown below:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee id="1">
    <name>Ashutosh</name>
    <email>[email protected]</email>
    <mobile>9999999999</mobile>
    <joiningDate>10-12-2010</joiningDate>
</Employee>

Unmarshalling

Below is a modified version of JAXBExecutor which perform unmarshalling. We unmarshall our employee.xml to employee object.

public class JAXBExecutor {
	
    public static void main(String args[]) throws JAXBException{
		
	File xml = new File("employee.xml");
		
	JAXBContext contx = JAXBContext.newInstance(Employee.class);
	Unmarshaller unmarshaller = contx.createUnmarshaller();

	Employee emp = (Employee)unmarshaller.unmarshal(xml);
	System.out.println("Emp Id: "+emp.getId());
	System.out.println("Emp Name: "+emp.getName());
	System.out.println("Emp Email: "+emp.getEmail());
	System.out.println("Emp Mobile: "+emp.getMobileNo());
	System.out.println("Emp Joining Date: "+emp.getJoiningDate());
    }
}

The JAXBExecutor above produces the following output:

Emp Id: 1
Emp Name: Ashutosh
Emp Email: [email protected]
Emp Mobile: 9999999999
Emp Joining Date: 10-12-2010
RELATED ARTICLES

Generate Namespace & Schema Information using JAXB

Most xml documents used in enterprise applications makes use of namespace to avoid element name conflicts. This article talks about generating these namespace and schema information when marshaling...

View Article

Handling Complex Types with JAXB Adapters

JAXB provides a convenient way to map complex data types to xml representations. JAXB provides XMLJavaAdapter to handle such custom marshalling and unmarshalling needs.

View Article

XML Schema Validation with JAXB

XML documents are often required to be validated against a schema, which contains some rules that the xml elements must respect. JAXB can be used to simplify this process of xml schema validation.

View Article