JAXB Example Tutorial

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

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.

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.

Above program creates following jaxb-emp.xml file.

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

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

By admin

Leave a Reply