Monday, May 15, 2023

How to converts Java Object to XML - JAXB Example

JAXB, which 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 an XML document (marshaling) and back to XML file into Java object(unmarshalling). It uses a combination of annotations and getters and setters to marshal Java objects into XML. JAXB actually defines the behavior of a standard set of tools and interfaces that automatically generate Java class files from an XML schema, remember JAXB is actually a framework and architecture, not an implementation. The package java.xml.bind provides a runtime binding framework for clients to marshal, unmarshal and validate XML files in Java.

By the way, 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. If you want to learn more about XML processing in Java, I suggest to look at chapter 2 of Core Java Volume 2 By Cay S. Horstmann. This book covers not only DOM and SAX but also StAX parser and locating information with XPath.



How to use JAXB in Java - An Example

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



@XmlRootElement
public class Item{
    private int id;
    private String name;
    private long price;
    
    public Item(){
        // no argument constructor required by JAXB
    }
    public Item(int id, String name, long price) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
    }

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

    @XmlElement
    public String getName() {
        return name;
    }

    @XmlElement
    public long getPrice() {
        return price;
    }   
    
}

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

Item dvd = new Item(101, "Lord of the Rings", 10);
JAXBContext context = JAXBContext.newInstance(Item.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(dvd, System.out);    

This will print the following XML String into your console :

How to use JAXB in Java with Example


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.

JAXB Example in Java


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

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
* Java program to convert Java object to XML Document using
* JAXB API. Converting a Java object to XML is also knonwn
* as marshalling and reverse process is called unmarshalling.
*
* @author Javin Paul
*/
public class JAXBDemo{

    public static void main(String args[]) throws JAXBException {

        final Item dvd = new Item(101, "Lord of the Rings", 10);
        final JAXBContext context = JAXBContext.newInstance(Item.class);
        final Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(dvd, System.out);       
    }
    
}

@XmlRootElement
class Item{
    private int id;
    private String name;
    private long price;
    
    public Item(){
        // no argument constructor required by JAXB
    }
    public Item(int id, String name, long price) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
    }

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

    @XmlElement
    public String getName() {
        return name;
    }

    @XmlElement
    public long getPrice() {
        return price;
    }
    
    
}



Things to keep in mind :

1) Your Java class must have a no-argument constructor, otherwise, JAXB will not able to marshal it. You will get the following Exception :
Exception in thread "main" 
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:
 1 counts of IllegalAnnotationExceptions
Item does not have a no-arg default constructor.
    at com.sun.xml.internal.bind.v2.runtime
.IllegalAnnotationsException$Builder.check(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime
.JAXBContextImpl.getTypeInfoSet(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime
.JAXBContextImpl.<init>(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime
.JAXBContextImpl.<init>(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.
JAXBContextImpl$JAXBContextBuilder.build(Unknown Source)
    at com.sun.xml.internal.bind.v2.ContextFactory.
createContext(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
    at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
    at javax.xml.bind.ContextFinder.find(Unknown Source)
    at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
    at javax.xml.bind.JAXBContext.newInstance(Unknown Source)


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.



That's all about how to convert Java Object to XML. In next tutorial you will learn how to do unmarshalling i.e. converting an XML back to Java object. Even though you might know about various XML parsers e.g. DOM, SAX and StAX, its good to know JAXP and JAXB as well. As Java and XML go hand and hand, they add another tool into the Java developer's arsenal.

If you are looking for some books to learn XML processing in Java, you can always refer core Java volume 2 for basic knowledge. It will give you nice overview of different parser, XML binding and XPath, but if you want to learn more in-depth then you can refer Java and XML by Brett McLaughlin. It's another good book to learn about XML processing in Java.

2 comments :

Anonymous said...

I am not sure, but I have never faced the no-arg constructor issue. I was using the Sun Metro JAR files for JAXB and SOAP web services in my application.

Anonymous said...

i want output as:



1
xyz
10000



i have list of phone from which i want to write each phone object into xml.
how can i do that?

Post a Comment