- UnMarshalling- How to convert XML to Java Objects using JAXB
- Sample XML Structure
- JAXB Unmarshaller Example
- Java Guides
- Unmarshaller example: Converting XML document into Java object
- XML Document
- Create POJO classes and Add JAXB annotations
- Book POJO Class
- Bootstore POJO Class
- Unmarshaller Class — Convert XML to Object in Java
UnMarshalling- How to convert XML to Java Objects using JAXB
This tutorial explains how to use JAXB (Java Architecture for XML Binding) to convert an XML document to Java Objects.
The previous tutorial has explained the conversion of Java Objects to XML.
As of Java 11, JAXB is not part of the JRE anymore, and you need to configure the relevant libraries via your dependency management system, for example, either Maven or Gradle.
Configure the Java compiler level to be at least 11 and add the JAXB dependencies to your pom file.
4.0.0 org.example JAXBDemo 0.0.1-SNAPSHOT JAXBDemo http://www.example.com UTF-8 11 11 junit junit 4.13.2 test com.sun.xml.bind jaxb-impl 2.3.3
Sample XML Structure
Terry Mathew female 30 married Manager +919999988822 abc@test.com 75000.0
Un-marshalling provides a client application the ability to convert XML data into JAXB-derived Java objects.
Let’s see the steps to convert XML document into java object.
- Create POJO Class
- Create the JAXBContext object
- Create the Unmarshaller objects
- Call the unmarshal method
- Use getter methods of POJO to access the data
Now, let us create the Java Objects (POJO) for the above XML.
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "EmployeeDetails") @XmlAccessorType(XmlAccessType.FIELD) //Define the order in which the fields are written in XML @XmlType(propOrder = < "firstName", "lastName", "gender", "age", "maritalStatus", "designation", "contactNumber","emailId", "salary" >) public class Employee < private String firstName; private String lastName; private int age; @XmlElement(name = "GrossSalary") private double salary; private String designation; private String contactNumber; private String emailId; private String gender; private String maritalStatus; public Employee() < super(); >// Getter and setter methods public String getFirstName() < return firstName; >public void setFirstName(String firstName) < this.firstName = firstName; >public String getLastName() < return lastName; >public void setLastName(String lastName) < this.lastName = lastName; >public int getAge() < return age; >public void setAge(int age) < this.age = age; >public double getSalary() < return salary; >public void setSalary(double salary) < this.salary = salary; >public String getDesignation() < return designation; >public void setDesignation(String designation) < this.designation = designation; >public String getContactNumber() < return contactNumber; >public void setContactNumber(String contactNumber) < this.contactNumber = contactNumber; >public String getEmailId() < return emailId; >public void setEmailId(String emailId) < this.emailId = emailId; >public String getGender() < return gender; >public void setGender(String gender) < this.gender = gender; >public String getMaritalStatus() < return maritalStatus; >public void setMaritalStatus(String maritalStatus) < this.maritalStatus = maritalStatus; >@Override public String toString() < return "Employee [FirstName=" + firstName + ", LastName=" + lastName + ", Age=" + age + ", Salary=" + salary + ", Designation=" + designation + ", ContactNumber=" + contactNumber + ", EmailId=" + emailId + ", Gender=" + gender + ", MaritalStatus=" + maritalStatus + "]"; >>
Create the following test program for reading the XML file. The XML file is present under src/test/resources.
Let’s use JAXB Unmarshaller to unmarshal our JAXB_XML back to a Java object:
import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.junit.Test; public class JAXBDeserialization < @Test public void JAXBUnmarshalTest() < try < String userDir = System.getProperty("user.dir"); File file = new File(userDir + "\\src\\test\\resources\\JAXB_XML.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Employee employee = (Employee) jaxbUnmarshaller.unmarshal(file); System.out.println("FirstName: " + employee.getFirstName()); System.out.println("LastName: " + employee.getLastName()); System.out.println("Age: " + employee.getAge()); System.out.println("Salary: " + employee.getSalary()); System.out.println("Contact Number: " + employee.getContactNumber()); System.out.println("Designation: " + employee.getDesignation()); System.out.println("Gender: " + employee.getGender()); System.out.println("EmailId: " + employee.getEmailId()); System.out.println("MaritalStatus: " + employee.getMaritalStatus()); >catch (JAXBException e) < e.printStackTrace(); >> >
When we run the code above, we may check the console output to verify that we have successfully converted XML data into a Java object:
The output of the above program is
There is another simple way of unmarshalling the XML to Java Objects.
@Test public void JAXBUnmarshalTest1() < try < String userDir = System.getProperty("user.dir"); File file = new File(userDir + "\\src\\test\\resources\\JAXB_XML.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Employee emp = (Employee) jaxbUnmarshaller.unmarshal(file); System.out.println(emp); >catch (JAXBException e) < e.printStackTrace(); >>
When we run the code above, we may check the console output to verify that we have successfully converted XML data into a Java object:
The output of the above program is
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
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. 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 );
Read the file using InputStream and pass it to the unmarshal() method.
Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new FileInputStream( "employee.xml" ));
Employee employee = (Employee) jaxbUnmarshaller.unmarshal( new URL( "http://localhost:8080/employee.xml" ) );
String xmlString = ". "; Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
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. 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.
--> //The default value is filled in the POJO.
3. 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.
4. 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 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"); >>
5. JAXB Unmarshaller Example
The following is an example of unmarshalling an XML document to Java Object.
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(); >> >
Before Unmarshaller Callback After Unmarshaller Callback Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]
Where employee.xml file is:
Drop me your questions in the comments section related to unmarshalling in java using JAXB.
Java Guides
In this article, we will learn how to convert XML to Java object using Java Architecture for XML Binding (JAXB).
Java Architecture for XML Binding (JAXB) is a Java standard that defines how Java objects are converted from and to XML. It uses a standard set of mappings.
In JAXB term Converting XML to Java Object is called JAXB Unmarshalling. JAXB API provides the UnMarshaller interface, we can unmarshal(read) the object into an XML document.
- Create POJO or bind the schema and generate the classes
- Create the JAXBContext object
- Create the Unmarshaller objects
- Call the unmarshal method
- Use getter methods of POJO to access the data
Unmarshaller example: Converting XML document into Java object
XML Document
xml version="1.0" encoding="UTF-8" standalone="yes"?> ns2:bookstore xmlns:ns2="net.javaguides.javaxmlparser.jaxb"> bookList> book> author>Joshua Blochauthor> title>Effective Javatitle> publisher>Amazonpublisher> isbn>978-0134685991isbn> book> book> author>Kathy Sierraauthor> title>Head First Java, 2nd Editiontitle> publisher>amazonpublisher> isbn>978-0596009205isbn> book> bookList> location>Newyorktlocation> name>Amazon Bookstorename> ns2:bookstore>
Create POJO classes and Add JAXB annotations
- @XmlRootElement: This is a must-have an annotation for the Object to be used in JAXB. It defines the root element for the XML content.
- @XmlType: It maps the class to the XML schema type. We can use it for ordering the elements in the XML.
- @XmlTransient: This will make sure that the Object property is not written to the XML.
- @XmlAttribute: This will create the Object property as an attribute.
- @XmlElement(name = “ABC”): This will create the element with name “ABC”
Book POJO Class
package net.javaguides.javaxmlparser.jaxb; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "book") @XmlType(propOrder = < "author", "name", "publisher", "isbn" >) public class Book < private String name; private String author; private String publisher; private String isbn; @XmlElement(name = "title") public String getName() < return name; > public void setName(String name) < this.name = name; > public String getAuthor() < return author; > public void setAuthor(String author) < this.author = author; > public String getPublisher() < return publisher; > public void setPublisher(String publisher) < this.publisher = publisher; > public String getIsbn() < return isbn; > public void setIsbn(String isbn) < this.isbn = isbn; > >
Bootstore POJO Class
package net.javaguides.javaxmlparser.jaxb; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(namespace = "net.javaguides.javaxmlparser.jaxb") public class Bookstore < @XmlElementWrapper(name = "bookList") @XmlElement(name = "book") private List Book > bookList; private String name; private String location; public void setBookList(List < Book > bookList) < this.bookList = bookList; > public List < Book > getBooksList() < return bookList; > public String getName() < return name; > public void setName(String name) < this.name = name; > public String getLocation() < return location; > public void setLocation(String location) < this.location = location; > >
Unmarshaller Class — Convert XML to Object in Java
package net.javaguides.javaxmlparser.jaxb; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; /** * Unmarshaller Class - Convert XML to Object in Java * @author Ramesh Fadatare * */ public class BookMain < private static final String BOOKSTORE_XML = "bookstore-jaxb.xml"; public static void main(String[] args) throws JAXBException, IOException < List Book > bookList = new ArrayList < Book > (); // create books Book book1 = new Book(); book1.setIsbn("978-0134685991"); book1.setName("Effective Java"); book1.setAuthor("Joshua Bloch"); book1.setPublisher("Amazon"); bookList.add(book1); Book book2 = new Book(); book2.setIsbn("978-0596009205"); book2.setName("Head First Java, 2nd Edition"); book2.setAuthor("Kathy Sierra"); book2.setPublisher("amazon"); bookList.add(book2); // create bookstore, assigning book Bookstore bookstore = new Bookstore(); bookstore.setName("Amazon Bookstore"); bookstore.setLocation("Newyorkt"); bookstore.setBookList(bookList); convertXMLToObject(); > private static Bookstore convertXMLToObject() < try < JAXBContext context = JAXBContext.newInstance(Bookstore.class); Unmarshaller un = context.createUnmarshaller(); Bookstore bookstore = (Bookstore) un.unmarshal(new File(BOOKSTORE_XML)); List Book > list = bookstore.getBooksList(); for (Book book: list) < System.out.println("Book: " + book.getName() + " from " + book.getAuthor()); > > catch (JAXBException e) < e.printStackTrace(); > return null; > >
Book: Effective Java from Joshua Bloch Book: Head First Java, 2nd Edition from Kathy Sierra