XML Parsing using JAXB

Kruti Dave
Dev Genius
Published in
4 min readApr 22, 2022

--

In this article, we will learn about XML parsing , different types of Parsers and annotations of JAXB which helps to convert XML to Java object and create XML from JAVA Object.

What is XML?

XML, eXtensible Markup Language is a markup language which defines a set of rules for encoding documents in a format that is readable.

What is XML Parser?

The XML parser is a software library or a package that provides an interface for the applications to work with XML documents. It checks for correct format of the XML document and also validates the XML documents.

There are several parsers for reading xml file in JAVA such as DOM Parser, SAX Parser, JAXB etc.

Let me give brief idea of each.

DOM Parser:

It creates a tree structure of objects available into the XML document and loads in into memory. It works on entire XML document. This API is very simple to use, it also supports Read and Write both operations. But also have some drawbacks, as it stores the entire document into memory if document size is big it will occupy more memory.

SAX Parser:

It is also known as the Simple API for XML. It can be consider as an event based parser as it does not store anything into memory and it start parsing at the beginning of the document in a sequence manner. Since SAX is more memory-efficient than DOM as it is based on events and works on callback mechanism.

JAXB:

JAXB — Java Architecture for XML Binding — is used to convert objects from/to XML.

JAXB offers a fast and suitable way to marshal (write) Java objects into XML and unmarshal (read) XML into Java objects. It supports Java annotations to map XML elements to Java attributes.

JAXB Annotations:

Let me give you a brief idea about JAXB annotations and usage of each.

  • @XmlRootElement

It defines the XML root element. When a top-level class (Root Class) is annotated with the @XmlRootElement annotation, then its value is represented as XML element in an XML document.

This is a must-have an annotation for the Object to be used in JAXB. It defines the root element for the XML content.

@XmlRootElement(name = "person")
public class Person implements Serializable {//other codes}
Output: person.xml<person id="1">
<name>Sample USer</name>
<email>sampleUser@gmail.com</email>
<phone>8777777777</phone>
</person>
  • @XmlAccessorType

This defines the fields or properties of your Java classes that the JAXB engine uses for including into generated XML. It accepts XmlAccessType values.

XmlAccessType .PUBLIC_MEMBER :

It means every public getter or setter and every public property defined in Java class will be automatically bound to XML, Annotated by XmlTransient will be excluded. It is also a default value for @XmlAccessorType.

XmlAccessType .FIELD:

It means fields which are non static and non transient will be automatically bound to XML; Annotated by XmlTransient will be excluded.

XmlAccessType .NONE:

It means any fields which are not annotated with JAXB annotations is not bound to XML.

XmlAccessType .PROPERTY:

It means every getter and setter pair will be automatically bound to XML, Annotated by XmlTransient will be excluded.

@XmlAccessorType(XmlAccessType.FIELD)
public class Person implements Serializable {}
  • @XmlAccessorOrder

Usage of this annotation of JAXB is to provide the order of fields and properties in a class. We can have predefined values ALPHABETICAL or UNDEFINED.

@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)
public class Person implements Serializable {}
  • @XmlType

It maps the class to the XML schema type. We can use it for ordering the elements in the XML.

@XmlRootElement(name = "person")
@XmlType(propOrder = {"userName",
"userEmailId",
"userPhoneNo",
"userCode"
})
public class Person implements Serializable {
//other code
}
  • @XmlElement

It define the actual XML element name that will be used while parsing.

@XmlElement(name = "name")
public void setUserName(String userName) {
this.userName = userName;
}
@XmlElement(name = "email")
public void setUserEmailId(String userEmailId) {
this.userEmailId = userEmailId;
}
@XmlElement(name = "phone")
public void setUserPhoneNo(String userPhoneNo) {
this.userPhoneNo = userPhoneNo;
}
Output: person.xml<person id="1">
<name>Sample USer</name>
<email>sampleUser@gmail.com</email>
<phone>8777777777</phone>
</person>

userName, userEmailId, userPhoneNo changed to name, email, phone after applying @XmlElement annotation on each property.

  • @XmlAttribute

It defines the id field which is mapped as an attribute instead of an element of an XML.

@XmlAttribute
public void setId(Long id) {
this.id = id;
}
Output: person.xml<person id="1">
</person>
  • @XmlTransient

This annotation defines on any fields than that we don’t want to be included in XML.

@XmlTransient
public void setActive(boolean isActive) {
this.isActive = isActive;
}
  • @XmlValue

This annotation can be used with a JavaBeans property and non static, non transient field. At most one field or property can be annotated with the @XmlValue annotation.

  • @XmlList

This annotation is used to map a property to a list simple type. It allows multiple values to be represented with whitespace separated in a single xml element.

@XmlList
private List<String> skills;
Output: person.xml<person id="1">
<name>Sample USer</name>
<email>sampleUser@gmail.com</email>
<phone>8777777777</phone>
<userCode>SUC102</userCode>
<skills>Skill-1 Skill-2 Skill-3</skills>
</person>
  • @XmlElementWrapper

This annotation is also used with collections. It generates a wrapper element around XML representation and inside that element it wills wrapper the collection elements. This must be used only with collections fields.

@XmlElementWrapper(name="goals")
@XmlElement(name="goal")
private List<String> goals;
Output: person.xml<person id="1">
<name>Sample USer</name>
<email>sampleUser@gmail.com</email>
<phone>8777777777</phone>
<userCode>SUC102</userCode>
<skills>Skill-1 Skill-2 Skill-3</skills>
<goals>
<goal>Goal-1</goal>
<goal>Goal-2</goal>
<goal>Goal-3</goal>
</goals>
</person>

I will cover JAXB annotation example by doing marshaling and unmarshaling in another Article.

Next Article : Marshaling and Unmarshaling XML using JAXB

Reference: JAXB Annotations

--

--

Experienced in Microservices using (Spring Boot and Spring Modules), Angular, Data Engineering (Python | Hadoop | PySpark | Hive | Airflow | ETL), AWS Services