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 javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBObjectToXmlFile {
    public static void main(String[] args) {
        Track track = new Track();
        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) {

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>

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.