HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / JAXB / JAXB Unmarshaller Example

JAXB Unmarshaller Example

The JAXB Unmarshaller interface is responsible for governing the process of deserializing the XML data to Java Objects. The unmarshalling to objects can be done to variety of input sources.

1. How to unmarshal XML to Object

1.1. Create Unmarshaller

Generally, to create Unmarshaller you can reuse this code.

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

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

1.2. Unmarshalling from an InputStream

InputStream inStream = new FileInputStream( "employee.xml" );

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

1.3. Unmarshalling from a URL

URL url = new URL( "http://localhost:8080/employee.xml" );

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

1.4. Unmarshalling the String content

String xmlString = "...";

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

1.5. Unmarshalling from a 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 );

2. JAXB Unmarshaller Properties

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

3. Unmarshaller Event Callbacks

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

  • void beforeUnmarshal(Unmarshaller unmarshaller, Object parent) {}
  • void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {}
package com.howtodoinjava.demo.model;

import java.io.Serializable;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.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");
	}
}

4. JAXB Unmarshaller Example

Example of unmarshalling XML file to Java Object.

package com.howtodoinjava.demo;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.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 comments section related to unmarshalling in java using jaxb.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. rathore

    February 27, 2020

    my Xml root element has an attribute the how to handle while unmarshalling..

  2. swetanand singh

    August 27, 2019

    The example given above is not working. After unmarshalling all the fields are zero.

    • Suresh A K

      September 27, 2019

      check whether you created a Department Entity class

  3. anonymous

    June 11, 2019

    if overriding of unmarshalling happens .how to resolve ?
    like if i have 2 JAXB resposnes like

    InputStream inStream = new FileInputStream( “employee.xml” );

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

    InputStream inStream2 = new FileInputStream( “studentxml” );

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

    if i did i am getting instream2 response as instream response .how to resolve this type of issues ?

  4. Moe

    April 3, 2019

    Hi,

    So after the unmarshalling if I want to turn the pojo into a json object to pass to the server, how would I do that?

  5. Jamal

    January 5, 2019

    could you please tell me from where employee.xml is there i mean your reading from resource path or any other path,please give me some examples how to read xml from resource path.

Comments are closed on this article!

Search Tutorials

JAXB Tutorial

  • JAXB – Annotations
  • JAXB – @XmlRootElement
  • JAXB – @XmlElementWrapper
  • JAXB – Marshaller
  • JAXB – Unmarshaller
  • JAXB – Convert XML to Java Object
  • JAXB – Convert JSON to Java Object
  • JAXB – Convert Java Object to XML
  • JAXB – Convert Java Object to JSON
  • JAXB – Map
  • JAXB – List and Set
  • JAXB – Generate Schema
  • JAXB – Schema Validation
  • JAXB – JAXBException
  • JAXB – IllegalAnnotationExceptions
  • JAXB – Marshal without @XmlRootElement
  • JAXB – Unmarshal without @XmlRootElement
  • Jackson 2 – Object from/to JSON
  • Jackson – Object from/to json
  • Jackson – JSON from/to Map

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces