How to convert an XML file into object using JAXB?

In this code snippet you can learn how to convert or unmarshall an XML file into it corresponding POJO. The steps on unmarshalling XML to object begin by creating an instance of JAXBContext. With the context object we can then create an instance of Unmarshaller class. Using the unmarshall() method and pass an XML file will give us the target POJO as the result.

Let’s see the code snippet below:

package org.kodejava.example.jaxb;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBXmlToObject {
    public static void main(String[] args) {
        try {
            File file = new File("Track.xml");
            JAXBContext context = JAXBContext.newInstance(Track.class);

            Unmarshaller unmarshaller = context.createUnmarshaller();
            Track track = (Track) unmarshaller.unmarshal(file);

            System.out.println("Track = " + track);
        } catch (JAXBException e) {

Here is the context of Track.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<track id="2">
    <title>She Loves You</title>


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply