JAXB: Marshalling and Unmarshalling Example

10 October 2012 By Nithya Vasudevan 20,568 views 4 Comments
8 Flares Twitter 0 Facebook 2 Google+ 6 8 Flares ×

Project Description

  • In this JAXB tutorial we will see an example on how to marshal and unmarshal Java objects.
  • This example explains how to,
    • map Java object’s property to XML element’s attribute using @XmlAttribute annotation,
    • map Java object’s property that references a class annotated with @XmlType as a child element to XML parent element.

Environment Used:

  • JDK 6.
  • Eclipse Indigo IDE for Java EE Developers.

New project in Eclipse

Create a new Java project in Eclipse IDE and name it as “SimpleJAXBDemo”.

Create Bean classes


Create a new Class “Address.java” in the package “com.theopentutorials.jaxb.to” and copy the following code.

package com.theopentutorials.jaxb.to;

import javax.xml.bind.annotation.XmlType;

public class Address {
	private String street;
	private String city;
	private String state;
	private long zip;
	public String getStreet() {
		return street;
	public void setStreet(String street) {
		this.street = street;
	public String getCity() {
		return city;
	public void setCity(String city) {
		this.city = city;
	public String getState() {
		return state;
	public void setState(String state) {
		this.state = state;
	public long getZip() {
		return zip;
	public void setZip(long zip) {
		this.zip = zip;
	public String toString() {
		return "Address [street=" + street + ", city=" + city + ", state="
				+ state + ", zip=" + zip + "]";

This is a bean class which is embedded in parent class (Employee) to create a child element (<address> tag). This class is annotated with @javax.xml.bind.annotation.XmlType.


Create a new Class “Employee.java” in the package “com.theopentutorials.jaxb.to” and copy the following code.

package com.theopentutorials.jaxb.to;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
public class Employee {

	private int id;
	private String name;
	private String department;
	private Address address;
	//Must have no-argument constructor
	public Employee() {	}
	public Employee(int id, String name, String department, Address address) {
		this.id = id;
		this.name = name;
		this.department = department;
		this.address = address;
	public int getId() {
		return id;
	public void setId(int id) {
		this.id = id;
	public String getName() {
		return name;
	public void setName(String name) {
		this.name = name;
	public String getDepartment() {
		return department;
	public void setDepartment(String department) {
		this.department = department;
	public Address getAddress() {
		return address;
	public void setAddress(Address address) {
		this.address = address;
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", department="
				+ department + ", address=" + address + "]";

This is the root/parent class containing JAXB annotations whose object is marshalled and unmarshalled.

  • @XmlAccessorType specifies whether annotations are applied to fields or Javabean properties (getters and setters).
  • @XmlRootElement specifies the XML element.
  • @XmlAttribute specifies XML element’s attribute.

Create JAXB Handler (Helper class)

Create a new Class “JAXBXMLHandler.java” in the package “com.theopentutorials.jaxb.xml” and copy the following code.

This is a helper class which has methods to perform marshalling and unmarshalling. These methods are called from client code (in this case, main() method).

  • Marshalling is the process of writing Java objects to XML file.
  • Unmarshalling is the process of converting XML content to Java objects.
package com.theopentutorials.jaxb.xml;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import com.theopentutorials.jaxb.to.Employee;

public class JAXBXMLHandler {

	// Export: Marshalling
	public static void marshal(Employee employee, File selectedFile)
			throws IOException, JAXBException {
		JAXBContext context;
		BufferedWriter writer = null;
		writer = new BufferedWriter(new FileWriter(selectedFile));
		context = JAXBContext.newInstance(Employee.class);
		Marshaller m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		m.marshal(employee, writer);

	// Import: Unmarshalling
	public static Employee unmarshal(File importFile) throws JAXBException {
		Employee employee = null;
		JAXBContext context;

		context = JAXBContext.newInstance(Employee.class);
		Unmarshaller um = context.createUnmarshaller();
		employee = (Employee) um.unmarshal(importFile);

		return employee;

Create Java Application client (main())

Create a new Class “JAXBDemo.java” in the package “com.theopentutorials.jaxb.main” and copy the following code.

package com.theopentutorials.jaxb.main;

import java.io.File;
import java.io.IOException;
import javax.xml.bind.JAXBException;
import com.theopentutorials.jaxb.to.Address;
import com.theopentutorials.jaxb.to.Employee;
import com.theopentutorials.jaxb.xml.JAXBXMLHandler;

public class JAXBDemo {
	public static void main(String[] args) {

		Address address = new Address();
		address.setStreet("2163, 1st Avenue");
		Employee employee = new Employee(1, "Kumar", "Development", address);
		try {
			//Marshalling: Writing Java object to XML file
			JAXBXMLHandler.marshal(employee, new File("employee.xml"));
			//Unmarshalling: Converting XML content to Java objects
			Employee employee2 = JAXBXMLHandler.unmarshal(new File("employee.xml"));
		} catch (IOException e) {
		} catch (JAXBException e) {
  • This class creates employee object and calls marshal method from JAXBXMLHandler helper class passing the employee object and the file to write the generated xml.
  • We call unmarshal method passing the marshalled file name which returns employee object.
  • Finally, printing the employee object (which calls toString() from Employee class).


Run the JAXBDemo.java.

Employee [id=1, name=Kumar, department=Development,
address=Address [street=2163, 1st Avenue, city=Peoria, state=Illinois, zip=61606]]

Refresh your project in Project Explorer (press F5 on your project) to see the generated XML file.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee id="1">
        <street>2163, 1st Avenue</street>

Folder Structure

The complete folder structure of this example is shown below.

Tags: , , , , , ,

  • Azarhudhin

    Hai Nithya,
    Your examples are simple and easy to understand , thanks for the posts, I have few queries regarding webservice security,if you can post reply will be helpful.

    I have a requirement for implementing the digital certificate at Webservice client, Please share the views If any.

    01. I have generated the client code using Axis2
    02. I have a certificate MyCertificate.cer generated as per the
    instructions from the Webservice Provider.
    03. I would like to establish the connection using the certificate through the webservice client, Please help how to handle

  • Prasanna Viswakumar


    Is it possible to unmarshal onto existing PoJos ? My requirement is to just
    update an existing PoJO retrieved from the DB with the ones provided by the
    user through XML. I wouldn’t want the fields untouched to be disturbed.\n
    The objects to be unmarshalled are not in my control. They can house any kind of member types, including other user-defined classes as well. In this case, it is possible to use reflection ? Should I also use Introspection ? Any examples available for the same ?

  • veer upadhyay

    hello mam,
    your this is really very simple, n easy to understand…
    Thank you.

  • vijai shanker

    Hello Folks,

    I am facing a problem these days regarding marshaling of map with JAXB at the time of using it with Restful web services.
    I am sending a map from client side but at service side it getting null…

    Please give me any suggestion….Thanks in Advance.