Home » Java » Enterprise Java » JAXB tutorial – Getting Started

About Arpit Mandliya

Arpit Mandliya
I am java developer at Tata Consultancy Services Ltd. My current area of interest are J2EE,web development and java design patterns. I am technology enthusiast trying to explore new technologies. In spare time,I love blogging.

JAXB tutorial – Getting Started

Note: Check out our JAXB Tutorial for Java XML Binding – The ULTIMATE Guide

What is JAXB?

JAXB stands for Java architecture for XML binding.It is used to convert XML to java object and java object to XML.JAXB defines an API for reading and writing Java objects to and from XML documents.Unlike SAX and DOM,we don’t need to be aware of XML parsing techniques.

There are two operations you can perform using JAXB

  1. Marshalling :Converting a java object to XML
  2. UnMarshalling :Converting a XML to java object

JAXB Tutorial

We will create a java program to marshal and unmarshal.

For Marshalling:

For Unmarshalling:

Java program:

With the help of annotations and API provided by JAXB,converting a java object to XML and vice versa become very easy.


A Java object which will be used to convert to and from XML

Create Country.java in src->org.arpit.javapostsforlearning.jaxb

package org.arpit.javapostsforlearning.jaxb;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

//Below annotation defines root element of XML file
//You can define order in which elements will be created in XML file
@XmlType(propOrder = { 'countryName', 'countryPopulation', 'listOfStates'})
public class Country {

 private String countryName;
 private double countryPopulation;

 private ArrayList<state> listOfStates;
 public Country() {

 public String getCountryName() {
  return countryName;
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 public double getCountryPopulation() {
  return countryPopulation;

 public void setCountryPopulation(double countryPopulation) {
  this.countryPopulation = countryPopulation;

 public ArrayList<state> getListOfStates() {
  return listOfStates;

 // XmLElementWrapper generates a wrapper element around XML representation
   @XmlElementWrapper(name = 'stateList')
  // XmlElement sets the name of the entities in collection
   @XmlElement(name = 'state')
 public void setListOfStates(ArrayList<state> listOfStates) {
  this.listOfStates = listOfStates;


@XmlRootElement:This annotation defines root element of XML file.
@XmlType(propOrder = {‘list of attributes in order’}):This is used to define order of elements in XML file.This is optional.
@XmlElement:This is used to define element in XML file.It sets name of entity.
@XmlElementWrapper(name = ‘name to be given to that wrapper’):It generates a wrapper element around XML representation.E.g.In above example, it will generate <stateList>
around each <state> element


package org.arpit.javapostsforlearning.jaxb;

import javax.xml.bind.annotation.XmlRootElement;

//Below statement means that class 'Country.java' is the root-element of our example
@XmlRootElement(namespace = 'org.arpit.javapostsforlearning.jaxb.Country')
public class State {

 private String stateName;
 long statePopulation;

 public State()

 public State(String stateName, long statePopulation) {
  this.stateName = stateName;
  this.statePopulation = statePopulation;

 public String getStateName() {
  return stateName;

 public void setStateName(String stateName) {
  this.stateName = stateName;

 public long getStatePopulation() {
  return statePopulation;

 public void setStatePopulation(long statePopulation) {
  this.statePopulation = statePopulation;


package org.arpit.javapostsforlearning.jaxb;

import java.io.File;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

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

  // creating country object
   Country countryIndia=new Country();  

   // Creating listOfStates
   ArrayList<state> stateList=new ArrayList<state>();
   State mpState=new State('Madhya Pradesh',1000000);
   State maharastraState=new State('Maharastra',2000000);


  try {

   // create JAXB context and initializing Marshaller
   JAXBContext jaxbContext = JAXBContext.newInstance(Country.class);
   Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

   // for getting nice formatted output
   jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

   //specify the location and name of xml file to be created
   File XMLfile = new File('C:\\arpit\\CountryRecord.xml');

   // Writing to XML file
   jaxbMarshaller.marshal(countryIndia, XMLfile); 
   // Writing to console
   jaxbMarshaller.marshal(countryIndia, System.out); 

  } catch (JAXBException e) {
   // some exception occured


After running above program,you will get following output

Console output:

<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<country xmlns:ns2='org.arpit.javapostsforlearning.jaxb.Country'>
            <stateName>Madhya Pradesh</stateName>

Now we will read above generated XML and retrieve country object from it.


package org.arpit.javapostsforlearning.jaxb;

import java.io.File;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

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

  try {

   // create JAXB context and initializing Marshaller
   JAXBContext jaxbContext = JAXBContext.newInstance(Country.class);

   Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

   // specify the location and name of xml file to be read
   File XMLfile = new File('C:\\arpit\\CountryRecord.xml');

   // this will create Java object - country from the XML file
   Country countryIndia = (Country) jaxbUnmarshaller.unmarshal(XMLfile);

   System.out.println('Country Name: '+countryIndia.getCountryName());
   System.out.println('Country Population: '+countryIndia.getCountryPopulation());

   ArrayList<state> listOfStates=countryIndia.getListOfStates();

   int i=0; 
   for(State state:listOfStates)
    System.out.println('State:'+i+' '+state.getStateName());

  } catch (JAXBException e) {
   // some exception occured


After running above program,you will get following output:

Console output:

Country Name: India
Country Population: 5000000.0
State:1 Madhya Pradesh
State:2 Maharastra

JAXB advantages:

  • It is very simple to use than DOM or SAX parser
  • We can marshal XML file to other data targets like inputStream,URL,DOM node.
  • We can unmarshal XML file from other data targets.
  • We don’t need to be aware of XML parsing techniques.
  • We don’t need to access XML in tree structure always.

JAXB disadvantages:

  • JAXB is high layer API so it has less control on parsing than SAX or DOM.
  • It has some overhead tasks so it is slower than SAX.

Source code:


Reference: JAXB tutorial – Getting Started from our JCG partner Arpit Mandliya at the Java frameworks and design patterns for beginners blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....




  1. Helpful one. Things are made understandy in simple way.
    It is good to see that you are a TCS employee.

  2. Very useful tutorial for me.
    Can anyone let me know how to run this code on tomcat server? what coding changes and web.xml , configurations are required

    • Prachi,
      u cann’t run this directly on tomcat as this program contains main method. How ever if u want to run on tomcat (u can call this method from the servlet class. prerequisites are that u shud have one servlet running class. u can search on google to run a simple servlet jsp program.

  3. Hi, I tried unmarshalling an xml into a java object, but when it comes to nested elements, i get null. It doesnt work with a list or even arraylist . where could i be going wrong? thanks.

  4. Very good tutorial. Easy to understand. However you can modify the tutorial to include an example of @XmlAttribute also. This would make this tutorial cover all the mostly used annotations. Thanks for efforts.

  5. any one help the steps to run this code in eclipse because am starting new to JAXB

  6. i want depth info about JAXB…can u tell me please….

  7. very good one for beginners, i want to append a node to child node. Please help me

  8. Hi, could you please upload the source code to another sharing site? When I try to download the source code I get this error:

    Error (509)
    This account’s public links are generating too much traffic and have been temporarily disabled!

  9. Thank you very much.
    Perfect example and perfectly explained!
    Really recommended, thank you again.

  10. During traversing the nested elements it gives null , could you suggest what could i have missed ?

Leave a Reply

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


Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.