Convert content of XML file to Java objects using JAXB

JAXB stands for Java Architecture for XML Binding. It is a library that uses annotations to convert Java objects to XML content and vice versa. In this tutorial, I will guide you all on how to convert content of XML file to Java objects using JAXB.

I’ll start with a Maven project like this:

The first thing you need to know about this JAXB library is that from Java 8 and earlier, the JAXB library was built-in with Java, which means you do not need to declare any JAXB dependencies to work with it. However, from Java 9 onwards, JAXB has been separated into an independent module.

If you are using Java EE 8, you can declare the following dependencies to work with JAXB:

If you use the Jakarta EE namespace for all versions from Java 9 onwards, declare the following dependency:

My project uses Java 21 so I will declare the namespace Jakarta EE with the implementation being the jaxb-impl library as follows:

To give an example for this tutorial, I have a simple XML file with the following contents:

And a Student class will be defined using the JAXB annotation as follows:

With JAXB, we usually use two basic annotations, which are:

  • @XmlRootElement: This annotation specifies what the outermost tag of an XML file is and thus it is declared at the beginning of a class.
  • @XmlElement: Used to declare a property of an object as a tag of an XML file.

In the above example, inside the <student> tag, we have three tags: <name>, <age> and <code>. Therefore, our Student object must declare the annotation for the three corresponding properties.

OK, now we will proceed to convert this XML content.

First, we will initialize the JAXBContext object with the object to be converted to, Student.

In this JAXBContext object, it has a method to create an object that converts XML content to a Java object: Unmarshaller. As follows:

And now you can use the unmarshal() method in the Unmarshaller object for our purposes.

There are many methods of overloaded unmarshal() but in this tutorial, we are working on the file so we will create the File object and pass it to the unmarshal() method.

Result:

Convert XML file content to Java object using JAXB

Full code:

Add Comment