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 org.kodejava.xml.support.Track;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.net.URL;
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) {
            e.printStackTrace();
        }
    }
}

Here is the context of Track.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<track id="2">
    <title>She Loves You</title>
</track>
package org.kodejava.xml.support;

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

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

    public Track() {
    }

    public Integer getId() {
        return id;
    }

    @XmlAttribute
    public void setId(Integer id) {
        this.id = id;
    }

    @XmlElement
    public String getTitle() {
        return title;
    }

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

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

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-ri</artifactId>
        <version>2.3.5</version>
        <type>pom</type>
    </dependency>
</dependencies>

Maven CentralMaven Central

Wayan

Leave a Reply

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