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

pom.xml
<dependency>
      <groupId>javax.xml.bind</groupId>
      <artifactId>jaxb-api</artifactId>
      <version>2.3.1</version>
</dependency>
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 -->
       <dependency>
           <groupId>jakarta.xml.bind</groupId>
           <artifactId>jakarta.xml.bind-api</artifactId>
           <version>2.3.2</version>
       </dependency>

       <!-- Runtime, com.sun.xml.bind module -->
       <dependency>
           <groupId>org.glassfish.jaxb</groupId>
           <artifactId>jaxb-runtime</artifactId>
           <version>2.3.2</version>
       </dependency>

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.

Book.java

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

@XmlRootElement(name = "Book")
@XmlAccessorType(XmlAccessType.PROPERTY)
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.

XMLToObject.java
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>
                       <id>1</id>
                       <name>Java</name>
                       <price>200</price>
                    </Book>
                    """;
            Book book = getBookFromString(xml);
            System.out.println(book.toString());
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    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;
    }
}

Output:

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;
}

Output:

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

References:

Happy Learning 🙂