JAXB @XmlRootElement annotation example

Lokesh Gupta

Java example of JAXB @XmlRootElement annotation in detail along with its usage during marshalling and unmarshalling operations.

1. JAXB @XmlRootElement annotation type

@XmlRootElement maps a class or an enum type to an XML element. When a top level class or an enum type is annotated with the @XmlRootElement annotation, then its value is represented as XML element in an XML document.

@XmlRootElement annotation can be used with the following annotations: XmlType, XmlEnum, XmlAccessorType, XmlAccessorOrder.

1.1. Syntax

//Without name attribute
@XmlRootElement             //1

//With name attribute         
@XmlRootElement(name = "employee")                //2

2. JAXB @XmlRootElement example

Now see few examples of how using @XmlRootElement changes the XML representations.

2.1. @XmlRootElement with ‘name’ attribute

@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class EmployeeData implements Serializable {

  private static final long serialVersionUID = 1L;

  private Integer id;
  private String firstName;
  private String lastName;
}

Above converts to:

<employee>
    <id>1</id>
    <firstName>Lokesh</firstName>
    <lastName>Gupta</lastName>
</employee>

2.2. @XmlRootElement without ‘name’ attribute

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class EmployeeData implements Serializable {

  private static final long serialVersionUID = 1L;

  private Integer id;
  private String firstName;
  private String lastName;
}

Above converts to:

<EmployeeData>
    <id>1</id>
    <firstName>Lokesh</firstName>
    <lastName>Gupta</lastName>
</EmployeeData>

Drop me your questions in comments section.

Happy Learning !!

Reference : XmlRootElement Java Doc

Comments

Subscribe
Notify of
guest

6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.