Convert XML file content to Java object 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 how to convert XML file content to Java object using JAXB.

I’ll start with a project like this:

Convert XML file content to Java object using JAXB

We 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