JAXB Example Tutorial

Filed Under: Java

Welcome to JAXB Example Tutorial. Java Architecture for XML Binding (JAXB) provides API for converting Object to XML and XML to Object easily. JAXB was developed as a separate project but it was used widely and finally became part of JDK in Java 6.

JAXB Tutorial

jaxb example, jaxb tutorial, jaxb, java object to xml, java xml to object

This tutorial is based on Java 7 and current JAXB version 2.0.

JAXB Marshalling: Converting a Java Object to XML.

JAXB Unmarhsalling: Converting XML to Java Object.

Using JAXB is very easy and it uses java annotations. We need to annotate Java Object to provide instructions for XML creation and then we have to create Marshaller to convert Object to XML.

Unmarshaller is used to convert XML to java Object.

JAXBContext is the entry point for JAXB and provides methods to get marshaller and unmarshaller object.

Some basic and useful JAXB annotations are:

  • @XmlRootElement: This is a must have annotation for the Object to be used in JAXB. It defines the root element for the XML content.
  • @XmlType: It maps the class to the XML schema type. We can use it for ordering the elements in the XML.
  • @XmlTransient: This will make sure that the Object property is not written to the XML.
  • @XmlAttribute: This will create the Object property as attribute.
  • @XmlElement(name = “abc”): This will create the element with name “abc”

There are some other JAXB annotation that you can learn from JAXB Official Site.

JAXB Example

Let’s run a simple JAXB example program to demonstrate the use of JAXB marshalling and unmarshalling.

package com.journaldev.xml.jaxb;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "Emp")
@XmlType(propOrder = {"name", "age", "role", "gender"})
public class Employee {

    private int id;

    private String gender;

    private int age;
    private String name;
    private String role;

    private String password;

    public String getPassword() {
        return password;

    public void setPassword(String password) {
        this.password = password;

    public int getId() {
        return id;

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

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public String getName() {
        return name;

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

    @XmlElement(name = "gen")
    public String getGender() {
        return gender;

    public void setGender(String gender) {
        this.gender = gender;

    public String getRole() {
        return role;

    public void setRole(String role) {
        this.role = role;

    public String toString() {
        return "ID = " + id + " NAME=" + name + " AGE=" + age + " GENDER=" + gender + " ROLE=" +
                role + " PASSWORD=" + password;


Employee is a normal java bean with private fields and their getters and setters. Notice the use of JAXB annotations to define root element, element name, elements order and transient property.

Here is a test JAXB example program showing JAXB Marshalling and JAXB Unmarshalling.

package com.journaldev.xml.jaxb;

import java.io.File;

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

public class JAXBExample {

    private static final String FILE_NAME = "jaxb-emp.xml";

    public static void main(String[] args) {
        Employee emp = new Employee();


        Employee empFromFile = jaxbXMLToObject();

    private static Employee jaxbXMLToObject() {
        try {
            JAXBContext context = JAXBContext.newInstance(Employee.class);
            Unmarshaller un = context.createUnmarshaller();
            Employee emp = (Employee) un.unmarshal(new File(FILE_NAME));
            return emp;
        } catch (JAXBException e) {
        return null;

    private static void jaxbObjectToXML(Employee emp) {

        try {
            JAXBContext context = JAXBContext.newInstance(Employee.class);
            Marshaller m = context.createMarshaller();
            //for pretty-print XML in JAXB
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            // Write to System.out for debugging
            // m.marshal(emp, System.out);

            // Write to File
            m.marshal(emp, new File(FILE_NAME));
        } catch (JAXBException e) {


Above program creates following jaxb-emp.xml file.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp id="1">

Check that XML file don’t have password field and we get following output when same XML file is unmarshalled to Object.

ID = 1 NAME=Pankaj AGE=25 GENDER=Male ROLE=Developer PASSWORD=null

That’s all for JAXB example tutorial, as you can see that it’s very easy to use.


  1. Hitesh Khandelwal says:

    what if we want to save multiple objects into a single XML files

    I am setting the values using constructor if like below :–

    Person p1 = new Person(“hitesh”, “kk”, 24,1056);

    Person p2 = new Person(“huhf”,”kjfs”,25,1026);

    As per above 2 objects I want to save both the objects into a single file I am using like below code but it is giving me complitaion error

    Can you please provide me any solution??

    marshaller.marshal(p1,p2,new File(“./src/person.xml”));

  2. Pankaj says:

    How can I set xml attribute like

  3. XmlTransientQuest says:

    We are using XJC to convert XML to POJO Classes. We are looking into options where some Objects can be made Transient. Is there a way in XJC where we can automatically make some ObjectProperty Transient ?

    For Example want to make the field Password Transient when using XJC to convert XSD to Java Object is there any annotations we can use in the bindings to xml that will help with this,

    private String password;

  4. nicoyao says:

    Your comment is awaiting moderation.

    How to distinguish the value by different variable type?

    Using your example:


  5. saj says:

    How to generate soap request by using webservices pls give me a simple example.

  6. Pj says:

    How to generate orm file using jaxb . THe orm file must be of this format

  7. manish says:

    how to use java object in javascript?

    1. Pankaj says:

      You can’t use java object in Javascript. You will have to convert it to XML or JSON and then send it to browser response. Then JS code can work on it.

  8. qwertz says:

    Nice explanation.
    Maybe you can help with that problem…
    What do I need to do if I don’t want JAXB to generate empty tags if the Java Object contains an Empty String?
    Example: String name = “”;
    don’t generate , just generate nothing.

    1. Pankaj says:

      See if marshal event callback works? Try with below method in your root object (@XmlRootElement annotated) and see how it goes.

      private void afterMarshal(Marshaller marshaller) {
              if("".equals(name)) {
                  name = null;
              } }
  9. Hemanth Kumar A says:

    Hi Pankaj,

    I have a requirement like I want to read the parent and child from the xml file like for ex:


  10. ishan bakshi says:

    what if the xml I am getting is in a nested format like this :


    king street

    How will i use the @XmlElement(name = “city”) over getCity() in the java object?

  11. Harish Kumar Garg says:

    I want to ask, can we convert XML into JAVA object dynamically. I don’t have XSD of that XML. POJO class should auto generate and XML data should accessible by JAVA object.
    Is it possible?

    1. Pankaj says:

      If you have XSD, you can use XJC to generate POJO classes. With only XML, it’s not possible because there is no contract that can be established. So you will have to write POJO classes manually in this case.

  12. Tayab Hussain says:

    excellent tutorial. great work by Pankaj as usual.

    1. Pankaj says:

      Thanks Tayab.

  13. shardul vaidya says:

    Excellent one ….

  14. sree says:

    Good Explanation.

  15. JerryC says:

    Very nice, and helpful. Thanks.

  16. Sagar Misal says:

    I am using Soap web service with log4j integrated with spring
    my problem is i want to skip password field to print in log file when its print all soap respose request xml in log file

  17. Manoj says:

    In some cases you have to deal with Java class which is not owned by you, and you can’t put jaxb annotations on the property, in that case Xstream api could be helpful. you can refer Xstream home page https://xstream.codehaus.org/ for more detail. There is a basic tutorial on Xstream at converting java object to xml you can refer that too.

  18. aditya says:

    how to convert bpel file into java

  19. Akshay Lokur says:


    How to convert Java Object inside of an object to XML?
    I mean instead of having “primitives” in an object , how object in an object gets marshalled to XML?

    Many thanks!

    1. Pankaj says:

      JAXB takes care of that automatically.

  20. Liams says:

    Could you help me i wanna transform XML to HTML and i am lose i don’t know how i began

  21. Devendra Varampati says:

    Please provide the xml to convert to java object complete code as early as possible

  22. lohith says:

    sir can you help me for this kind of xml to convert to java object complete code as early as possible



Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors