How do I change the XML root element name in JAXB?

In the following code snippet you will learn how to change the default root element name of the XML generated by the JAXB API. By default, the name of the class is use as the root element name. To change the root element name we can use the name property of the @XmlRootElement annotation. In the Customer model below we change the root element name into cust.

package org.kodejava.xml;


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

@XmlRootElement(name = "cust")
@XmlType(propOrder = {"id", "name", "address"})
public class Customer {
    private Integer id;
    private String name;
    private Address address;

    public Integer getId() {
        return id;

    public void setId(Integer id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public Address getAddress() {
        return address;

    public void setAddress(Address address) {
        this.address = address;

public class Address {
    private String street;
    private String city;
    private String province;
    private String zipcode;
    private String country;

    // Getters & Setters
package org.kodejava.xml;


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

public class JAXBCustomRootElement {
    public static void main(String[] args) {
        Customer customer = new Customer();
        customer.setName("Johnny Mnemonic");

        Address address = new Address();
        address.setStreet("Sunset Road");

        try {
            JAXBContext context = JAXBContext.newInstance(Customer.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(customer, System.out);
        } catch (JAXBException e) {

When we convert this POJO to XML using JAXB API we will get the following result:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <name>Johnny Mnemonic</name>
        <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.