JAXB (Java Architecture for XML Binding) is a java framework that allows the developers to map java objects to XML. Here we are going to see how to convert an XML to Java Object.

JAXB XML to Java Object:

JAXB provides two main features – that are marshalling and unmarshalling. Marshalling allows us to convert Java objects to XML whereas unmarshalling used to convert XML to Object.

In this example, let’s see how to unmarshal the XML.

XML to Java Object Conversion:

Add the below jaxb-api dependency in pom.xml

Note: Java 1.9+ users have to use the below dependencies to get the jaxb-api, you can follow this StackOverflow thread for complete details.
java-1.9+ pom.xml
<!-- API, java.xml.bind module -->

       <!-- Runtime, com.sun.xml.bind module -->

Now time to implement the logic to convert XML to Object.

XML String to Java Object:

Create a Java class that can be mapped with XML.


import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Book")
public class Book {
    private int id;
    private String name;
    private double price;

    // getters and setters
    // tostring

The above book class is the representation of the XML so that JAXB can map the XML fields to the book properties. The below program is to convert the XML string to Object.

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;

public class XMLToObject {
    public static void main(String[] args){
        try {
            String xml = """
            Book book = getBookFromString(xml);
        } catch (JAXBException e) {

    public static Book getBookFromString(String xml) throws JAXBException{
        JAXBContext jc = JAXBContext.newInstance(Book.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource streamSource = new StreamSource(new StringReader(xml));
        JAXBElement<Book> jaxbElement = unmarshaller.unmarshal(streamSource, Book.class);

        Book book = jaxbElement.getValue();
        return book;


Book{id=1, name='Java', price=200.0}

XML file to Java Object:

We can even pass the XML file to JAXB context to convert the XML to object. In the below method instead of passing the XML string, parsing XML file as an input to the unmarshaller.

public static Book getBookFromFile() throws JAXBException{
    File file = new File("book.xml"); // XML file path
    JAXBContext jc = JAXBContext.newInstance(Book.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Book book = (Book)unmarshaller.unmarshal(file);
    return book;


Book{id=1, name='Java', price=200.0}


Happy Learning 🙂