JAXB @XmlRootElement Annotation Example

Lokesh Gupta

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

1. @XmlRootElement Annotation

The @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 an XML element in an XML document.

2. Syntax

We can use the annotation without providing a specific name. In the following example, the XML tag will be generated as “<Employee>

@XmlRootElement

public class Employee implements Serializable {
  
  //...
}

Or, we can provide a specific name to the generated XML tag. In the following example, the XML tag will be generated as “<employee>

@XmlRootElement(name = "employee")
public class Employee implements Serializable {
  
  //...
}

The @XmlRootElement annotation can be used with the following annotations:

  • @XmlType
  • @XmlEnum
  • @XmlAccessorType
  • @XmlAccessorOrder
@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee implements Serializable { 
  //...
}

2. JAXB @XmlRootElement Example

Now see a 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;
}

The 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;
}

The above converts to:

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

Drop me your questions in the comments section.

Happy Learning !!

Source Code on Github

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.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode