Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Monday, May 15, 2023

JAXB XML Binding tutorial - Marshalling UnMarshalling Java Object to XML Example

XML binding is a concept of generating Java objects from XML and opposite i.e. XML documents from Java objects. 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 a Java object, modify a Java object, and then converting back to an XML file.

Once you have an XML document as a 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 relies on POJO(Plain old Java objects) and annotations.

And, If you are a Java beginner then you can also join these Java Programming and development courses 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, or to redirect the generated XML documents.

How to use JAXB for Marshalling UnMarshalling Java Object to XML Example

Benefits of Using JAXB for XML binding in Java:

Though there are a couple of options available to bind XML documents as Java objects including the popular Apache XMLBeans library, JAXB has some advantages. 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.

Marshalling XML to Java object and XML binding using JAX example tutorial

How to bind XML document to Java object using JAXB

In this section, we will see a complete code example of how to generate XML documents from Java objects first and then converting XML documents to Java objects using JAXB API. In this example, we have used a simple Booking class that represents booking data. Following is the sample XML document which will be generated 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.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){ = name; = 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) { = contact;}

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

    public String getName() { return name; }
    public void setName(String 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 the JAXB example. Converting XML documents to Java objects 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.

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.;jsessionid=AB538194BC4072064351E49E971328BB

Anonymous said...

Jaxb is most expensive and not supports multithreading

Anonymous said...

JAXB acronym is Java Architecture for XML Binding

Post a Comment