Sunday, June 14, 2015

How to convert Java Object to XML - JAXB Example

JAXB, stands for Java API for XML Binding or sometimes Java Architecture for XML Binding is a decade old technology to directly convert a Java object into XML document (marshaling) and back to XML file into Java object(unmarshalling).It uses combination of annotations and getters and setters to marshal Java object into XML.

What is JAXB?

JAXB actually defines the behavior of a standard set of tools and interfaces that automatically generate Java class files from XML schema, remember JAXB is actually a framework and/or an architecture, not an implementation.

The package java.xml.bind provides a runtime binding framework for clients to marshal, unmarshal and validate XML file in Java. BTW, JAXB is not the only option to parse XML in Java, you can always use SAX or DOM parser or JAXP API to convert XML to Java object and vice-versa.

How to use JAXB in Java

Let's see how you can use JAXB to create XML document from Java classes This is how JAXB works, let's say you have a Item object that needs to be converted to XML document, all you need to do is create a class Item with getters and annotate them appropriately as shown below :

Then you create a marshaller from JAXBContext class and ask it to convert an instance of class Item into XML, as shown below :

This will print following XML String into your console :

You can see how easy it is to convert a Java object to XML using JAXB. You don't need to worry about mapping types, opening tag, closing tag or doing anything related to XML by hand.

Important Points to Remember

  1. Your Java class must have a no-argument constructor, otherwise JAXB will not able to marshal it. You will get following Exception :

  2. Always remember to annotate your Java class with @XmlRootElement annotation, this would be your main tag in XML and each property using @XmlElement, they will appear as child element of the main tag.


Here is the complete Java program to convert a Java object to XML file using JAXB API :



No comments:

Post a Comment