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.xml;


import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.util.Objects;

public class JAXBXmlToObject {
    public static void main(String[] args) {
        try {
            URL resource = JAXBXmlToObject.class.getResource("/Track.xml");
            File file = new File(Objects.requireNonNull(resource).toURI());
            JAXBContext context = JAXBContext.newInstance(Track.class);

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

            System.out.println("Track = " + track);
        } catch (Exception 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>

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

public class Track {
    private Integer id;
    private String title;

    public Track() {

    public Integer getId() {
        return id;

    public void setId(Integer id) { = id;

    public String getTitle() {
        return title;

    public void setTitle(String title) {
        this.title = title;

    public String toString() {
        return "Track{" +
                "id=" + id +
                ", title='" + title + '\'' +

Maven Dependencies


Maven Central Maven Central


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.