Tuesday, January 24, 2017

JAXB XML Binding tutorial - Marshalling UnMarshalling Java Object to XML

XML binding is a concept of generating Java objects from XML and opposite i.e. XML documents from Java object. Along with parsing XML documents using DOM and SAX parser, XML binding is a key concept to learn if you are working in a Java application that uses XML in any way e.g. for storing persistence data like user preferences or for transmitting messages between two systems, etc. XML binding is also a popular XML Interview question in Java. JAXB and XMLBeans are two common ways to achieve XML binding in Java.  XML binding, also known as XML marshaling and marshaling has two sides, first converting an XML document to Java object, modify Java object, and then converting back to an XML file.

Once you have an XML document as Java object, You can use the power of Java programming language to process and manipulate the XML elements, attributes, etc. In the last couple of Java XML tutorials, we have seen How to parse XML using DOM parser and How to evaluate XPATH expression in Java

In this Java XML tutorial, we will talk about JAXB (Java API for XML Binding) which is an annotation-based library integrated into Java SDK. The beauty of JAXB is that it doesn't require XML Schema to generate XML documents from Java objects unlike XMLBeans and simply rely on POJO(Plain old Java objects) and annotations.

And, If you are new to Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.

Steps to Create XML from Java using JAXB:

1) Create a POJO and annotate with @XmlRootElement @XmlAccessorType and annotate all fields with @XmlElement. This will bind Object properties to XML elements
2) Create a JAXBContext
3) Create a Marsaller object and call marshal() method on that. While marshaling you can pass either java.io.Writer, java.io.File or java.io.OutputStream to redirect the generated XML documents.

Benefits of Using JAXB for XML binding in Java:

Marshalling XML to Java object and XML binding using JAX example tutorialThough there are couple of options available to bind XML document as Java object including popular Apache XMLBeans library, JAXB has some advantage. Following are some of the benefits of using JAXB for XML binding in Java :

1) JAXB is available in JDK so it doesn't require any external library or dependency in Classpath.

2) JAXB doesn't require XML schema to work. Though you can use XML Schema for generating corresponding Java classes and its pretty useful if you have large and complex XML Schema which will result in huge number of classes but for simple usage you can just annotate your object with relevant XML annotations provided by JAXB package i.e. java.xml.binding and you are good to go.

3) JAXB is pretty easy to understand and operate. Just look at the below example of generationg an XML file form Java class , what it requires is couple of annotations like @XmlRootElement and @XmlAccessorType along with four lines of code.

4) Modifying XML files in Java is much easier using JAXB as compared to other XML parsers like DOM and SAX because you only deal with POJOs

5) JAXB is more memory efficient than DOM or SAX parser.

How to bind XML document to Java object using JAXB

In this section we will see complete code example of how to generate XML documents from Java object first and than converting XML documents to Java object using JAXB API. In this example we have used a simple Booking class which represent booking data. Following is the sample XML document which will be generate in this JAXB example of marshaling and unmarshaling XML documents.


Here is the Java class which uses JAXB for creating XML document from Java object and vice-versa.

import java.io.StringReader;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

 * JAXB example to generate xml document from Java object also called xml marshaling
 * from Java object or xml binding in Java.
 * @author  Javin Paul

public class JAXBXmlBindExample {
    public static void main(String args[]){
        //Creating booking object for marshaling into XML document
        Booking booking = new Booking();
        DateFormat formatter = new SimpleDateFormat("dd/MM/yy");
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = formatter.parse("11/09/2012");
            endDate = formatter.parse("14/09/2012");
        } catch (ParseException ex) {
                                                                         null, ex);
        JAXBContext jaxbCtx = null;
        StringWriter xmlWriter = null;
        try {
            //XML Binding code using JAXB
            jaxbCtx = JAXBContext.newInstance(Booking.class);
            xmlWriter = new StringWriter();
            jaxbCtx.createMarshaller().marshal(booking, xmlWriter);
            System.out.println("XML Marshal example in Java");
            Booking b = (Booking) jaxbCtx.createUnmarshaller().unmarshal(
                                               new StringReader(xmlWriter.toString()));
            System.out.println("XML Unmarshal example in JAva");
        } catch (JAXBException ex) {
                                                                          null, ex);

class Booking{
    private String name;
    private int contact;
    private Date startDate;
    private Date endDate;
    private String address;
    public Booking(){}
    public Booking(String name, int contact, Date startDate, Date endDate, String address){
        this.name = name;
        this.contact = contact;
        this.startDate = startDate;
        this.endDate = endDate;
        this.address = address;

    public String getAddress() { return address; }
    public void setAddress(String address) {this.address = address; }

    public int getContact() { return contact; }
    public void setContact(int contact) {this.contact = contact;}

    public Date getEndDate() { return endDate; }
    public void setEndDate(Date endDate) { this.endDate = endDate; }

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

    public Date getStartDate() { return startDate; }
    public void setStartDate(Date startDate) { this.startDate = startDate; }

    public String toString() {
        return "Booking{" + "name=" + name + ", contact=" + contact + ", startDate=" + startDate + ", endDate=" + endDate + ", address=" + address + '}';



XML Marshal example in Java
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><booking><name>Rohit</name><contact>983672431</contact><startDate>2012-09-11T00:00:00-04:30</startDate><endDate>2012-09-14T00:00:00-04:30</endDate><address>Mumbai</address></booking>

XML Unmarshal example in JAva
Booking{name=Rohit, contact=983672431, startDate=Tue Sep 11 00:00:00 VET 2012, endDate=Fri Sep 14 00:00:00 VET 2012, address=Mumbai}

If you look at this example carefully, we have just one class Booking which is annotated with JAXB annotation and a Test class that performs the job of XML binding in Java. In the first section, we have created a Booking object and later converted it into an XML file as shown in the output. In the second part, we have used the same XML String to create Java object and that Java object is printed in the console.

That’s all on How to do XML binding in Java using JAXB example. Converting XML documents to Java object or marshaling gives you immense power of Java programming language to perform any enrichment, normalization or manipulating XML elements, attributes, and text in XML documents.

Further Learning
Java In-Depth: Become a Complete Java Engineer!
Master Java Web Services and REST API with Spring Boot
Java Web Fundamentals

Related Java and XML tutorials from Javarevisited blog


Anonymous said...

Please explain annotations like @XmlAccessorType(XmlAccessType.FIELD) can have value 'XmlAccessType.METHOD'. How it differs than FIELD?

Anonymous said...

Do you have a reference for your comment,
"JAXB is more memory efficient than DOM or SAX parser?"

danial said...

for masrahlling and unmarshalling java objects, jaxb is the most efficent choice.

Anonymous said...

Jaxb is most expensive and not supports multithreading

Anonymous said...

JAXB acronym is Java Architecture for XML Binding

Post a Comment