What is JAXB ?

In this tutorial, we will learn What is JAXB ? 

JAXB is Java Architecture for XML Binding. It is a standard way to bind XML schemas and Java representations to incorporate XML data and processing functions in Java applications.

JAXB is an API for reading and writing Java objects to and from XML documents. JAXB provides methods for Marshalling java objects into XML and Unmarshalling an XML into its original java object.

JAXB provides annotations to implement marshalling and unmarshalling. Some of the annotations in JAXB are:

Some of the Annotations in JAXB:

AnnotationDescription
XmlRootElementDefines the root element for the XML that need to be produced.
XmlTypeSpecify the order in which XML elements will be produced.
XmlElementMaps a JavaBean property to an XML element.
XmlTransientAnnotate the fields that we do not want to be included in XML with this annotation.
XmlSchemaMaps a package name to a XML namespace.

Let’s explore the above annotations one by one.

@XmlRootElement:

This annotation defines the root element for the XML to be produced. The purpose is to uniquely associate a root element with a class. @XmlRootElement annotation can be used to map a class or enum type to XML type.

@XmlType:

This annotation specifies the order in which XML elements or JSON output will be produced. To specify the order propOrder with XmlType annotation is used. This annotation can be used as shown below:

@XmlType(propOrder={“name”, “age” , “salary”, “dept”}))

Here the propOrder is a list of names of JavaBean properties in the class. Each name in the list is the name of a Java identifier of the JavaBean property. The order in which JavaBean properties are listed is the order of XML Schema elements to which the JavaBean properties are mapped.

All of the JavaBean properties being mapped to XML Schema elements must be listed in the propOrder. A JavaBean property or field listed in propOrder must not be transient or annotated with @XmlTransient.

@XmlElement:

This annotation maps a JavaBean property to an XML element. This annotation can be used with following elements:

  • A JavaBean property
  • Non static, non transient field
  • Within XmlElements

@XmlTransient:

If you don’t want the fields in the object to be included in the xml that will be generated, then use this annotation. This revents the mapping of a JavaBean property to XML representation.

@XmlSchema:

This annotation maps a package name to a XML namespace. Thi is a package level annotation.

Let’s see the Marshalling and Unmarshalling with an example by using the above annotations.

Marshalling and Unmarshalling with an example.

Related posts

Leave a Comment