How to generate a wrapper element around XML representation in JAXB?

In this example you’ll learn how to use the JAXB @XmlElementWrapper annotation. This annotation can be used to generate a wrapper element around an XML element representation. When no name defined, the @XmlElementWrapper annotation uses the property name as the wrapper element name. Let’s see the code snippet below.

Here is the code snippet for marshaling the Record object into an XML document. Before the marshalling take place, we create an object of Record and adds a some Track into it.

package org.kodejava.xml;

import org.kodejava.xml.support.Track;
import org.kodejava.xml.support.Record;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class JAXBElementWrapper {
    public static void main(String[] args) {
        Track track1 = new Track();
        track1.setId(1);
        track1.setTitle("Love Me Do");

        Track track2 = new Track();
        track2.setId(2);
        track2.setTitle("From Me To You");

        Track track3 = new Track();
        track3.setId(3);
        track3.setTitle("She Loves You");

        Record record = new Record();
        record.setId(1);
        record.setTitle("The Beatles 1");
        record.getTracks().add(track1);
        record.getTracks().add(track2);
        record.getTracks().add(track3);

        try {
            JAXBContext context = JAXBContext.newInstance(Record.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(record, System.out);

            try (Writer writer = new FileWriter("Record.xml")) {
                marshaller.marshal(record, writer);
            }
        } catch (JAXBException | IOException e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.xml.support;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;

@XmlRootElement
public class Record {
    private Integer id;
    private String title;
    private String artist;
    private String genre;
    private Integer year;
    private List<Track> tracks = new ArrayList<>();

    public Record() {
    }

    @XmlAttribute
    public Integer getId() {
        return id;
    }

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

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

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

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public String getGenre() {
        return genre;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }

    public Integer getYear() {
        return year;
    }

    public void setYear(Integer year) {
        this.year = year;
    }

    @XmlElementWrapper(name = "trackList")
    @XmlElement(name = "track")
    public List<Track> getTracks() {
        return tracks;
    }

    public void setTracks(List<Track> tracks) {
        this.tracks = tracks;
    }

    @Override
    public String toString() {
        return "Record{" +
                "title='" + title + "'\n" +
                ", artist='" + artist + "'\n" +
                ", genre='" + genre + "'\n" +
                ", year=" + year +
                '}';
    }
}
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 + '\'' +
                '}';
    }
}

The above program will generated the following XML document.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<record id="1">
    <title>The Beatles 1</title>
    <trackList>
        <track id="1">
            <title>Love Me Do</title>
        </track>
        <track id="2">
            <title>From Me To You</title>
        </track>
        <track id="3">
            <title>She Loves You</title>
        </track>
    </trackList>
</record>

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

How to convert object to XML using JAXB?

JAXB, Java Architecture for XML Binding, it uses JAXB annotations to convert POJO to or from XML file. In this example you will learn how to convert an object / POJO into an XML document using JAXB. The process of converting an object into XML also known as marshalling. In this snippet our POJO is a class called Track as you can see below.

The first thing that we need to do is to annotate the Track POJO with a couple of JAXB annotations. For this example we add the @XmlRootElement, @XmlElement and @XmlAttribute annotations.

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 + '\'' +
                '}';
    }
}

After we have the Track class annotated we can use the code snippet below to convert the POJO into XML. The step to take is to start by creating an instance of JAXBContext. From this context object we create the Marshaller object. To convert it to XML we called the marshall() method. The method have many overloads, in this case we just want to print the XML to the System.out.

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;

public class JAXBObjectToXml {
    public static void main(String[] args) {
        Track track = new Track();
        track.setId(1);
        track.setTitle("Hey Jude");

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

            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(track, System.out);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

If you run this code you will get the following output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<track id="1">
    <title>Hey Jude</title>
</track>

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

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