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.example.jaxb;

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>

Leave a Reply

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