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;


    @XmlTransient
    public String getPassword() {
        return password;
    }


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


    @XmlAttribute
    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;
    }


    @Override
    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();
        emp.setId(1);
        emp.setAge(25);
        emp.setName("Pankaj");
        emp.setGender("Male");
        emp.setRole("Developer");
        emp.setPassword("sensitive");

        jaxbObjectToXML(emp);

        Employee empFromFile = jaxbXMLToObject();
        System.out.println(empFromFile.toString());
    }


    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) {
            e.printStackTrace();
        }
        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) {
            e.printStackTrace();
        }
    }

}

Above program creates following jaxb-emp.xml file.


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp id="1">
    <name>Pankaj</name>
    <age>25</age>
    <role>Developer</role>
    <gen>Male</gen>
</Emp>

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.

Comments

  1. 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,

    @XMLTransient
    private String password;

  2. nicoyao says:

    Your comment is awaiting moderation.

    How to distinguish the value by different variable type?

    Using your example:

    <name>”Pankaj”</name>
    <age>25</age>
    <role>”Developer”</role>
    <gen>”1″</gen>

  3. saj says:

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

  4. Pj says:

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

  5. 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.

  6. 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.
    Thanks!!

    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;
              } }
      
  7. 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:

    aaa
    30

  8. ishan bakshi says:

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

    Pankaj
    25
    Developer
    Male

    king street
    SF
    USA

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

  9. 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.

  10. Tayab Hussain says:

    excellent tutorial. great work by Pankaj as usual.

  11. shardul vaidya says:

    Excellent one ….

  12. sree says:

    Good Explanation.

  13. JerryC says:

    Very nice, and helpful. Thanks.

  14. 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

  15. 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 http://xstream.codehaus.org/ for more detail. There is a basic tutorial on Xstream at converting java object to xml you can refer that too.

  16. aditya says:

    how to convert bpel file into java

  17. Akshay Lokur says:

    Pankaj,

    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.

  18. Liams says:

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

  19. Devendra Varampati says:

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

  20. lohith says:

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

    lohith
    raj

    25
    Developer
    Male

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages