HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / JAXB / JAXB Annotations

JAXB Annotations

Learn about JAXB annotations in detail along with their usage during marshalling and unmarshalling operations.

1) List of JAXB Annotations

AnnotationScopeDescription
@XmlRootElementClass, EnumDefines the XML root element. Root Java classes need to be registered with the JAXB context when it is created.
@XmlAccessorTypePackage, ClassDefines 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.
@XmlAccessorOrderPackage, ClassDefines the sequential order of the children.
@XmlTypeClass, EnumMaps a Java class to a schema type. It defines the type name and order of its children.
@XmlElementFieldMaps a field or property to an XML element
@XmlAttributeFieldMaps a field or property to an XML attribute
@XmlTransientFieldPrevents mapping a field or property to the XML Schema
@XmlValueFieldMaps a field or property to the text value on an XML tag.
@XmlListField, ParameterMaps a collection to a list of values separated by space.
@XmlElementWrapperFieldMaps 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 by XmlTransient.
  • 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 by XmlTransient.
  • PUBLIC_MEMBER – Every public getter/setter pair and every public field will be automatically bound to XML, unless annotated by XmlTransient.
  • 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

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. DUSHYANT SINGH

    June 10, 2020

    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

  2. George

    May 11, 2020

    Very good Tutorial!!! Thanks!!

  3. Huda

    September 23, 2019

    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

      September 23, 2019

      Try XmlElements

  4. manikandan

    August 17, 2019

    This tutorial is very very nice and easy to understand clearly.

  5. khushboo

    May 6, 2019

    How to read a xml node that can either have further xmlElements or value

    value

    valueId

  6. kumar

    March 30, 2019

    how to specify size for a string? i want to use @xmlElement with @size annotation, but its not working, please let me know

  7. pawan

    February 1, 2019

    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

Comments are closed on this article!

Search Tutorials

JAXB Tutorial

  • JAXB – Annotations
  • JAXB – @XmlRootElement
  • JAXB – @XmlElementWrapper
  • JAXB – Marshaller
  • JAXB – Unmarshaller
  • JAXB – Convert XML to Java Object
  • JAXB – Convert JSON to Java Object
  • JAXB – Convert Java Object to XML
  • JAXB – Convert Java Object to JSON
  • JAXB – Map
  • JAXB – List and Set
  • JAXB – Generate Schema
  • JAXB – Schema Validation
  • JAXB – JAXBException
  • JAXB – IllegalAnnotationExceptions
  • JAXB – Marshal without @XmlRootElement
  • JAXB – Unmarshal without @XmlRootElement
  • Jackson 2 – Object from/to JSON
  • Jackson – Object from/to json
  • Jackson – JSON from/to Map

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces