Learn about JAXB annotations in detail along with their usage during marshalling and unmarshalling operations.
1) List of JAXB Annotations
Annotation | Scope | Description |
---|---|---|
@XmlRootElement | Class, Enum | Defines the XML root element. Root Java classes need to be registered with the JAXB context when it is created. |
@XmlAccessorType | Package, Class | Defines the fields and properties of your Java classes that the JAXB engine uses for binding. It has four values: PUBLIC_MEMBER , FIELD , PROPERTY and NONE . |
@XmlAccessorOrder | Package, Class | Defines the sequential order of the children. |
@XmlType | Class, Enum | Maps a Java class to a schema type. It defines the type name and order of its children. |
@XmlElement | Field | Maps a field or property to an XML element |
@XmlAttribute | Field | Maps a field or property to an XML attribute |
@XmlTransient | Field | Prevents mapping a field or property to the XML Schema |
@XmlValue | Field | Maps a field or property to the text value on an XML tag. |
@XmlList | Field, Parameter | Maps a collection to a list of values separated by space. |
@XmlElementWrapper | Field | Maps a Java collection to an XML wrapped collection |
Read More : Convert Java Object to XML
1.1) @XmlRootElement
This maps a class or an enum type to an XML root 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(name = "employee") @XmlAccessorType(XmlAccessType.PROPERTY) public class Employee implements Serializable { //More code }
Above will result into:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <employee> //.... </employee>
1.2) @XmlAccessorType
It defines the fields or properties of your Java classes that the JAXB engine uses for including into generated XML. It has four possible values.
FIELD
– Every non static, non transient field in a JAXB-bound class will be automatically bound to XML, unless annotated byXmlTransient
.NONE
– None of the fields or properties is bound to XML unless they are specifically annotated with some of the JAXB annotations.PROPERTY
– Every getter/setter pair in a JAXB-bound class will be automatically bound to XML, unless annotated byXmlTransient
.PUBLIC_MEMBER
– Every public getter/setter pair and every public field will be automatically bound to XML, unless annotated byXmlTransient
.- Default value is
PUBLIC_MEMBER
.
@XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.FIELD) public class Employee implements Serializable { private Integer id; private String firstName; private String lastName; }
Above will result into:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <employee> <firstName>Lokesh</firstName> <id>1</id> <lastName>Gupta</lastName> </employee>
1.3) @XmlAccessorOrder
Controls the ordering of fields and properties in a class. You can have predefined values ALPHABETICAL
or UNDEFINED
.
@XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.FIELD) public class Employee implements Serializable { private Integer id; private String firstName; private String lastName; private Department department; }
Above will result into:
<?xml version="1.0" encoding="UTF-8"?> <employee> <department> <id>101</id> <name>IT</name> </department> <firstName>Lokesh</firstName> <id>1</id> <lastName>Gupta</lastName> </employee>
1.4) @XmlType
It maps a Java class or enum type to a schema type. It defines the type name, namespace and order of its children. It is used to match the element in the schema to element in the model.
@XmlRootElement(name = "employee") @XmlType(propOrder={"id", "firstName" , "lastName", "department" }) public class Employee implements Serializable { private Integer id; private String firstName; private String lastName; private Department department; }
1.5) @XmlElement
Maps a JavaBean property to an XML element derived from property name.
@XmlRootElement(name = "employee") public class Employee implements Serializable { @XmlElement(name=employeeId) private Integer id; @XmlElement private String firstName; private String lastName; private Department department; }
Above will result into:
<?xml version="1.0" encoding="UTF-8"?> <employee> <employeeId>1</employeeId> <firstName>Lokesh</firstName> </employee>
1.6) @XmlAttribute
Maps a JavaBean property to an XML attribute.
@XmlRootElement(name = "employee") public class Employee implements Serializable { @XmlAttribute private Integer id; private String firstName; private String lastName; private Department department; }
Above will result into:
<?xml version="1.0" encoding="UTF-8"?> <employee id="1"> <department> <id>101</id> <name>IT</name> </department> <firstName>Lokesh</firstName> <lastName>Gupta</lastName> </employee>
1.7) @XmlTransient
Prevents the mapping of a JavaBean property/type to XML representation. When placed on a class, it indicates that the class shouldn’t be mapped to XML by itself. Properties on such class will be mapped to XML along with its derived classes as if the class is inlined.
@XmlTransient
is mutually exclusive with all other JAXB defined annotations.
@XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.FIELD) public class Employee implements Serializable { @XmlTransient private Integer id; private String firstName; private String lastName; private Department department; }
Above will result into:
<?xml version="1.0" encoding="UTF-8"?> <employee> <firstName>Lokesh</firstName> <lastName>Gupta</lastName> <department> <id>101</id> <name>IT</name> </department> </employee>
1.8) @XmlValue
Enables mapping a class to an XML Schema complex type with a simpleContent or an XML Schema simple type. It’s more related to schema mapping to model mapping.
1.9) @XmlList
Used to map a property to a list simple type. It allows multiple values to be represented as whitespace-separated tokens in a single element.
@XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.FIELD) public class Employee implements Serializable { private List<String> hobbies; } // <?xml version="1.0" encoding="UTF-8"?> <employee> <hobbies>Swimming</hobbies> <hobbies>Playing</hobbies> <hobbies>Karate</hobbies> </employee>
After using @XmlList
, observe the output.
@XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.FIELD) public class Employee implements Serializable { @XmlList private List<String> hobbies; } // <?xml version="1.0" encoding="UTF-8"?> <employee> <hobbies>Swimming Playing Karate</hobbies> </employee>
]
1.10) @XmlElementWrapper
Generates a wrapper element around XML representation. This is primarily intended to be used to produce a wrapper XML element around collections. So, it must be used with collection property.
@XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.FIELD) public class Employee implements Serializable { @XmlElementWrapper(name="hobbies") @XmlElement(name="hobby") private List<String> hobbies; }
Above will result into:
<?xml version="1.0" encoding="UTF-8"?> <employee> <hobbies> <hobby>Swimming</hobby> <hobby>Playing</hobby> <hobby>Karate</hobby> </hobbies> </employee>
2) JAXB Annotation Example
Learn to apply JAXB annotations on model classes and then marshal the object into the XML file.
package com.howtodoinjava.demo.model; import java.io.Serializable; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.FIELD) public class Employee implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String firstName; private String lastName; private Department department; @XmlElementWrapper(name="hobbies") @XmlElement(name="hobby") private List<String> hobbies; public Employee() { super(); } public Employee(int id, String fName, String lName, Department department) { super(); this.id = id; this.firstName = fName; this.lastName = lName; this.department = department; } //Setters and Getters }
package com.howtodoinjava.demo; import java.io.File; import java.util.Arrays; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import com.howtodoinjava.demo.model.Department; import com.howtodoinjava.demo.model.Employee; public class JaxbExample { public static void main(String[] args) { Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT")); employee.setHobbies(Arrays.asList("Swimming","Playing", "Karate")); jaxbObjectToXML(employee); } private static void jaxbObjectToXML(Employee employee) { try { JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // To format XML //Print XML String to Console jaxbMarshaller.marshal(employee, new File("employee.xml")); } catch (JAXBException e) { e.printStackTrace(); } } }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <employee> <id>1</id> <firstName>Lokesh</firstName> <lastName>Gupta</lastName> <department> <id>101</id> <name>IT</name> </department> <hobbies> <hobby>Swimming</hobby> <hobby>Playing</hobby> <hobby>Karate</hobby> </hobbies> </employee>
Drop me your questions in comments section.
Happy Learning !!
Reference: JAXB Annotations Java Doc
DUSHYANT SINGH
Hi, Thanks for sharing the concepts.
The problem i am facing, is that my xml annotations are getting ignored, hence attributes are also appearing as elements. I am using spring boot.
Kindly guide me with the possible wayout.
Thank You
Dushyant
George
Very good Tutorial!!! Thanks!!
Huda
In my model class how do I map two different xml elements to one variable?
In the below example I am mapping xml element “SN” to string named “sn”. I also want to map xml element “ST” to string variable “sn”
@XmlElement(name = “SN”)
private String sn;
How do I achieve that?
Lokesh Gupta
Try XmlElements
manikandan
This tutorial is very very nice and easy to understand clearly.
khushboo
How to read a xml node that can either have further xmlElements or value
value
valueId
kumar
how to specify size for a string? i want to use @xmlElement with @size annotation, but its not working, please let me know
pawan
How to add xsi:type to XML tag like this?
weekly downtime
weekly downtime
3
a2791c168612d09cfceb437177cec4ed
End User Applications
WEEKLY
2019-01-31T14:00:00-08:00
2019-01-31T14:45:00-08:00
America/Chicago
SUNDAY
THURSDAY
MONDAY
FRIDAY