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.example.jaxb;
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;
@XmlElement
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
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"?>
<cust>
<id>1</id>
<name>Johnny Mnemonic</name>
<address>
<street>Sunset Road</street>
<city>Denpasar</city>
<province>Bali</province>
<postCode>800000</postCode>
<country>Indonesia</country>
</address>
</cust>
Latest posts by Wayan (see all)
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
- How do I get a list of all TimeZones Ids using Java 8? - April 25, 2020