JAXB Tutorial

In this tutorial, we will learn how to convert Java objects from and to XML using Java Architecture for XML Binding (JAXB).
Java Architecture for XML Binding (JAXB) is a Java standard that defines how Java objects are converted from and to XML. It uses a standard set of mappings.
JAXB defines an API for reading and writing Java objects to and from XML documents.
Let's familiar with terms like Marshalling and Unmarshalling.
  • JAXB Marshalling means Converting a Java Object to XML.
  • JAXB Unmarshalling means Converting XML to Java Object.
Two important JAXB classes are:
  • Unmarshaller interface is used to convert XML to Java Object.
  • JAXBContext class is the entry point for JAXB and provides methods to get marshaller and unmarshalled object.
JAXB 2.0 provides support to annotations so less coding is required to develop JAXB application. The javax.xml.bind.annotation package provides classes and interfaces for JAXB 2.0.
This is simple get starting JAXB tutorial, you can learn in-depth about JAXB on official JAXB Users Guide.
Some basic and useful JAXB annotations are:
  1. @XmlRootElement: This is a must have an annotation for the Object to be used in JAXB. It defines the root element for the XML content.
  2. @XmlType: It maps the class to the XML schema type. We can use it for ordering the elements in the XML.
  3. @XmlTransient: This will make sure that the Object property is not written to the XML.
  4. @XmlAttribute: This will create the Object property as an attribute.
  5. @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.

Technologies used in this article

  • JDK 1.8
  • JAXB 2.0
Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion.
So far we have seen basic concepts of JAXB, now let's develop a program to demonstrate the use of JAXB marshalling and unmarshalling.

Create a User class and Add JAXB annotations

package net.javaguides.javaxmlparser.jaxb;

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

@XmlRootElement(name = "Users")
@XmlType(propOrder = {
    "id",
    "firstName",
    "lastName",
    "age",
    "gender"
})
public class User {
    private int id;
    private String firstName;
    private String lastName;
    private int age;
    private String gender;
    private String password;

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

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

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

    public String getGender() {
        return gender;
    }

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

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

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

    @Override
    public String toString() {
        return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", gender=" +
            gender + "]";
    }
}
Note that we have applied JAXB annotations to define root element, element name, elements order, and transient property.

Convert Java Object to XML - JAXB Marshalling

Here is a program for JAXB Marshalling (Converting a Java Object to XML):
package net.javaguides.javaxmlparser.jaxb;

import java.io.File;

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

public class ConvertObjectToXML {
    private static final String FILE_NAME = "jaxb-users.xml";

    public static void main(String[] args) {
        User user = new User();
        user.setId(1);
        user.setAge(25);
        user.setFirstName("Ramesh");
        user.setGender("Male");
        user.setLastName("Fadatare");
        user.setPassword("sensitive");

        jaxbObjectToXML(user);
    }

    private static void jaxbObjectToXML(User user) {

        try {
            JAXBContext context = JAXBContext.newInstance(User.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(user, System.out);

            // Write to File
            m.marshal(user, new File(FILE_NAME));
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}
Above program creates following jaxb-users.xml file.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Users id="1">
    <firstName>Ramesh</firstName>
    <lastName>Fadatare</lastName>
    <age>25</age>
    <gender>Male</gender>
</Users>
Note that XML file doesn’t have password field because this field is annotated with @XmlTransient annotation.
Check out more examples on How to Convert Java Object to XML - JAXB Marshalling

Convert XML to Java Object - JAXB Unmarshalling

Here is a program for JAXB Unmarshalling (Convert XML to Java Object):
package net.javaguides.javaxmlparser.jaxb;

import java.io.File;

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

public class ConvertXMLToObject {
    private static final String FILE_NAME = "jaxb-users.xml";

    public static void main(String[] args) {
        User userFromFile = jaxbXMLToObject();
        System.out.println(userFromFile.toString());
    }

    private static User jaxbXMLToObject() {
        try {
            JAXBContext context = JAXBContext.newInstance(User.class);
            Unmarshaller un = context.createUnmarshaller();
            User user = (User) un.unmarshal(new File(FILE_NAME));
            return user;
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }
}
An output of above program is:
User [id=1, firstName=Ramesh, lastName=Fadatare, age=25, gender=Male]
Note that output does not print password field on console because this field is annotated with @XmlTransient annotation.
Check out more examples on How to Convert XML to Java Object - JAXB Unmarshalling
That’s all for JAXB example tutorial, as you can see that it’s very easy to use.
This is simple get starting JAXB tutorial, you can learn in-depth about JAXB on official JAXB Users Guide.

Comments