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
NAMAN GOYAL
I’m returning a class’s object using @XmlRootElement annotation …. But at runtime it is giving
HTTP Status 500 – Internal Server Error
Type Status Report
Message Internal Server Error
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
while there is no output on console… HELP !!
Lokesh Gupta
Please share the stack trace.
surabhi priya
If i want a ArrayList in my XML how should we do that ?
Johnny
How to avoid root element? For example:
I have java classes Application and Person.
I get xml structure like this:
And I would want xml structure to be:
Lokesh Gupta
Here root node is “application”. It is not possible (also not advisable) to avoid “person” node.