How do I define the XML element order in JAXB?

In this code snippet you will learn how to define the order of XML element generated by the JAXB API. To define the element order we need to use the @XmlType annotation in our POJO. This annotation propOrder attribute is where we define what element should come first and which element should be place at the end.

The XML generated by the marshaller below will have the following order: street, city, province, zipcode and country as the last XML element.


import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

public @XmlRootElement(name = "customerAddress")
@XmlType(propOrder = {"street", "city", "province", "zipcode", "country"})
class Address {
    private String street;
    private String city;
    private String province;
    private String country;
    private String zipcode;

    public String getStreet() {
        return street;

    public void setStreet(String street) {
        this.street = street;

    public String getCity() {
        return city;

    public void setCity(String city) { = city;

    public String getProvince() {
        return province;

    public void setProvince(String province) {
        this.province = province;

    public String getCountry() {
        return country;

    public void setCountry(String country) { = country;

    public String getZipcode() {
        return zipcode;

    public void setZipcode(String zipCode) {
        this.zipcode = zipCode;

    public String toString() {
        return "Address{" +
                "street='" + street + '\'' +
                ", city='" + city + '\'' +
                ", province='" + province + '\'' +
                ", country='" + country + '\'' +
                ", zipcode='" + zipcode + '\'' +

Now, let’s create a program to run the marshalling process of the Address POJO to convert it into XML document:

package org.kodejava.xml;


import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBElementOrder {
    public static void main(String[] args) {
        Address address = new Address();
        address.setStreet("Sunset Road");

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

            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(address, System.out);
        } catch (JAXBException e) {

And it will give you the following output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <street>Sunset Road</street>

Maven Dependencies


Maven Central Maven Central


Leave a Reply

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