How to create an XML file of a POJO using JAXB?

The code snippet below show you how to convert POJO into XML file using JAXB. To do this we can pass the output file where we want the XML to be saved to the marshaller object.

package org.kodejava.xml;

import org.kodejava.xml.support.Track;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;

public class JAXBObjectToXmlFile {
    public static void main(String[] args) {
        Track track = new Track();
        track.setId(2);
        track.setTitle("She Loves You");

        try {
            JAXBContext context = JAXBContext.newInstance(Track.class);

            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            File output = new File("Track.xml");
            marshaller.marshal(track, output);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

This snippet will create a file called Track.xml with the following content:

<?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 Central Maven Central

Wayan

Leave a Reply

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