Friday, 2 January 2015

What is Unmarshlling in Java ?

Unmarshalling:  Unmarshalling means converting from XML file to Java Object.
UnMarshaller interface is used to unmarshal(read) the object from  xml document.
In below example we are going to convert simple xml document into java object.

Steps to convert XML document into java object.

>Create POJO 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

Save as  employee.xml

<?xml version="1.0" encoding="UTF-8" ?>
 <employee id="216">
 <name>Vishwa Kumar</name>
 <salary>38000.00</salary>
 <company>Jaarwis</company>
 </employee>

Save as  Employee.java

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

 @XmlRootElement
 public class Employee {
 private int id;
 private String name;
 private float salary;
 private String company
 public Employee() {}
 public Employee(int id, String name, float salary,String company) {
 super();
 this.id = id;
 this.name = name;
 this.salary=salary;
 this.company = company;
 }
 @XmlAttribute
 public int getId() {
 return id;
 }
 public void setId(int id) {
 this.id = id;
 }
 @XmlElement
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 @XmlElement
 public float getSalary() {
 return salary;
 }
 public void setSalary(float salary) {
 this.salary = salary;
 }
 @XmlElement
 public float getCompany() {
 return company;
 }
 public void setCompany(String company) {
 this.company = company;
 }
 }

 Save as   XmlToObject.java

 import java.io.File;
 import javax.xml.bind.JAXBContext;
 import javax.xml.bind.JAXBException;
 import javax.xml.bind.Unmarshaller;

 public class XmlToObject {
 public static void main(String []args) {
 try {

 File file = new File("employee.xml");
 JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
 Employee emp= (Employee) jaxbUnmarshaller.unmarshal(file);
 System.out.println("Employee Id: "+emp.getId() );
 System.out.println("Employee Name: "+emp.getName() );
 System.out.println("Employee Salary: "+emp.getSalary() );
 System.out.println("Employee Company Name: "+emp.getCompany );
 }
 catch(AXBException e)
   {
 e.printStackTrace();
   }
  }
 }

 Output:

 Employee Id: 216
 Employee Name: Vishwa Kumar
 Employee Salary: 38000.00
 Employee Company Name: Jaarwis




No comments:

Post a Comment