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")
@XmlType(propOrder = {
public class Course {

    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) { = id;
        this.attendees = attendees; = name;
        this.description = description; = date;

    public long getId() {
        return id;

    public void setId(long 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) { = name;

    public String getDescription() {
        return description;

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

    public Date getDate() {
        return date;

    public void setDate(Date 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);


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Course id="1">
    <description>Learning Java Architecture for XML Binding(JAX-B)</description>

You may also like...