JAXB UnMarshalling Example – Convert XML to Java Object

Previously we have learnt how to convert a Java Object into XML using JAXB Marshalling Technique. Now let’s learn the vice-versa converting XML back to Java Object

JAXB Dependency

We will be requiring the below two jars to be put in the classpath for performing the unmarshalling operation.

  1. jaxb-api.jar
  2. jaxb-impl.jar

Student.java

Our Student class is a simple POJO class containing three properties name,age,id. We will be using 2 main annotations namely @XmlRootElement(Maps Class to XML element) and @XmlElement(Maps Bean property to XML element).

package com.javainterviewpoint.jaxb;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Student 
{
    String name;
    String age;
    int id;
    public String getName() {
        return name;
    }
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    @XmlElement    
    public void setAge(String age) {
        this.age = age;
    }
    public int getId() {
        return id;
    }
    @XmlElement
    public void setId(int id) {
        this.id = id;
    }
}

UnMarshal_Example.java

We will be performing the below steps to convert XML into Object

  • JaxbContext is created by passing the class reference of the student class.
  • Call the createUnmarshaller() method of the context above created, to get the object of the Unmarshaller.
  • unmarshal() method is called which converts the XML into Student object.
package com.javainterviewpoint.jaxb;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class UnMarshal_Example 
{
    public static void main(String args[])
    {
        try 
        {
            //Create jaxbContext
            JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);
            //Getting UnMarshaller object
            Unmarshaller jaxbUnMarshaller = jaxbContext.createUnmarshaller();
            //Converting Student.xml to st object
            Student st = (Student)jaxbUnMarshaller.unmarshal(new File("D:\\JIP\\Student.xml"));
            //Print the elements of student object "st"
            System.out.println(" Student Id   : "+st.getId());
            System.out.println(" Student Name : "+st.getName());
            System.out.println(" Student Age  : "+st.getAge());
        } catch (JAXBException e) 
        {
            e.printStackTrace();
        }
    }
}

Output :

 Student Id   : 12
 Student Name : JavaInterviewPoint
 Student Age  : 11

Leave a Reply

Your email address will not be published. Required fields are marked *