Convert Java Object to XML specific order using JAX-B

Sometimes you want to generate an XML with elements in a specific order. With JAX-B this is very easy. Just annotate your class with the @XmlType annotation and add the property order using propOrder which takes a String list of the property names. That’s all!

The Model

package com.memorynotfound.xml.jaxb;

import javax.xml.bind.annotation.*;
import java.util.Date;

@XmlRootElement(name = "Course")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {
        "date",
        "name",
        "description",
        "attendees"
})
public class Course {

    @XmlAttribute
    private long id;
    private int attendees;
    private String name;
    private String description;
    private Date date;

    /**
     * Default no-args constructor needed by JAX-B
     */
    public Course() {
    }

    public Course(long id, int attendees, String name, String description, Date date) {
        this.id = id;
        this.attendees = attendees;
        this.name = name;
        this.description = description;
        this.date = date;
    }

    public long getId() {
        return id;
    }

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

    public int getAttendees() {
        return attendees;
    }

    public void setAttendees(int attendees) {
        this.attendees = attendees;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

Convert Java Object to XML specific order

package com.memorynotfound.xml.jaxb;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.util.Date;

public class ConvertObjectToXml {

    public static void main(String... args) throws JAXBException {
        // create the object
        Course course = new Course(1, 53, "JAX-B", "Learning Java Architecture for XML Binding(JAX-B)", new Date());

        // create jaxb context
        JAXBContext jaxbContext = JAXBContext.newInstance(Course.class);

        // create jaxb marshaller
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // pretty print xml
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        // marshal object
        jaxbMarshaller.marshal(course, System.out);
    }
}

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Course id="1">
    <date>2014-12-25T13:03:34.430+01:00</date>
    <name>JAX-B</name>
    <description>Learning Java Architecture for XML Binding(JAX-B)</description>
    <attendees>53</attendees>
</Course>

You may also like...