JAXB Unmarshaller Example

The JAXB Unmarshaller interface is responsible for governing the process of deserializing XML to Java Objects. The unmarshalling of objects can be done to a variety of input sources such as URL, File, FileInputStream, StreamSource, org.w3.dom.Node, SAXSource, XMLStreamReader or XMLEventReader.

1. Maven

Start with adding the latest ‘jakarta‘ dependencies for adding the JAXB support (Java 11 onwards).

<dependencies>
  <dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>4.0.0</version>
  </dependency>
</dependencies>

<dependencies>
  <dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>4.0.3</version>
    <scope>runtime</scope>
  </dependency>
</dependencies>

2. How to Unmarshal XML to POJO

We can create an Unmarshaller instance using createUnmarshaller() method and then use the unmarshal() method to perform the unmarshalling.

Note that the POJO should be annotated with @XmlRootElement annotation. This is the simplest mode of unmarshalling.

JAXBContext jaxbContext 	= JAXBContext.newInstance( Employee.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

//Overloaded methods to unmarshal from different xml sources
Employee employee = (Employee) jaxbUnmarshaller.unmarshal( xmlSource );

2.1. Read XML from InputStream

Read the file using InputStream and pass it to the unmarshal() method.

Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new FileInputStream( "employee.xml" ));

2.2. Read XML from a URL

Employee employee = (Employee) jaxbUnmarshaller.unmarshal( new URL( "http://localhost:8080/employee.xml" ) );

2.3. Read an XML String

String xmlString = "...";

Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new StringReader(xmlString));

2.4. Using org.w3c.dom.Node

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File( "employee.xml")); //Node

Employee employee = (Employee) jaxbUnmarshaller.unmarshal( document );

3. Handling Default Values

JAXB unmarshaller fills a field’s default value when the document’s corresponding XML element is present, but the element content is missing. In short, the element is an empty XML tag.

<foo>
  <a/>  <!-- or <a></a> -->  //The default value is filled in the POJO.
</foo>

4. JAXB Unmarshaller Properties

There currently are no properties required to be supported by all JAXB Providers on Unmarshaller. However, some providers may support their own set of provider-specific properties.

5. Unmarshaller Event Callbacks

We can customize the unmarshalling operation by adding the callback methods inside JAXB annotated classes e.g. Employee.java. We need to define two methods that will listen before and after the Unmarshaller process that class.

  • void beforeUnmarshal(Unmarshaller unmarshaller, Object parent) {}
  • void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {}
import java.io.Serializable;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Employee implements Serializable {
 
  private static final long serialVersionUID = 1L;
 
  private Integer id;
  private String firstName;
  private String lastName;
  private Department department;
 
  public Employee() {
    super();
  }
 
  //Setters and Getters
 
  @Override
  public String toString() {
    return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", department="
        + department + "]";
  }
 
  // It is called immediately after the object is created and before the unmarshalling begins.
  // The callback provides an opportunity to initialize JavaBean properties prior to unmarshalling.
  void beforeUnmarshal(Unmarshaller unmarshaller, Object parent) {
    System.out.println("Before Unmarshaller Callback");
  }
 
  // It is called after all the properties are unmarshalled for this object,
  // but before this object is set to the parent object.
  void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
    System.out.println("After Unmarshaller Callback");
  }
}

5. JAXB Unmarshaller Example

The following is an example of unmarshalling an XML document to Java Object.

import java.io.File;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import com.howtodoinjava.demo.model.Employee;
 
public class JaxbExample 
{
  public static void main(String[] args) 
  {
    String fileName = "employee.xml";
 
    jaxbXmlFileToObject(fileName);
  }
 
  private static void jaxbXmlFileToObject(String fileName) {
     
    File xmlFile = new File(fileName);
     
    JAXBContext jaxbContext;
    try
    {
      jaxbContext = JAXBContext.newInstance(Employee.class);
      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
       
      Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile);
       
      System.out.println(employee);
    }
    catch (JAXBException e) 
    {
      e.printStackTrace();
    }
  }
}

Program Output.

Before Unmarshaller Callback
After Unmarshaller Callback

Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

Where employee.xml file is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <department>
        <id>101</id>
        <name>IT</name>
    </department>
    <firstName>Lokesh</firstName>
    <id>1</id>
    <lastName>Gupta</lastName>
</employee>

Drop me your questions in the comments section related to unmarshalling in java using JAXB.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode