Saturday, 20 August 2016

JAXB: map xml to Java object

In previous post, I explained how to convert java object to XML document. In this post, I am going to explain how to convert xml to Java object.

Step 1: Define model object, that maps xml document .

Step 2: Get JAXBContext instance using Employee model class.
JAXBContext contextObj = JAXBContext.newInstance(Employee.class);

Step 3: Get Unmarshaller instance using contextObj.

Unmarshaller unMarshaller = contextObj.createUnmarshaller();

Step 4: Call unmarshal method, to map given xml document to Java object.
Employee emp1 = (Employee) unMarshaller.unmarshal(new File("/Users/harikrishna_gurram/Documents/employee.xml"));

Following is the complete working application.


employee.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee id="1">
    <firstName>Hari krishna</firstName>
    <lastName>Gurram</lastName>
</employee>


Employee.java
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "", propOrder = { "id", "firstName", "lastName" })
@XmlRootElement(name = "employee")
public class Employee {
 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 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;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
 }

}


Test.java
import java.io.File;

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

public class Test {
 public static void main(String args[]) throws JAXBException {
  JAXBContext contextObj = JAXBContext.newInstance(Employee.class);

  Unmarshaller unMarshaller = contextObj.createUnmarshaller();

  Employee emp1 = (Employee) unMarshaller.unmarshal(new File("/Users/harikrishna_gurram/Documents/employee.xml"));

  System.out.println(emp1);
 }
}


Output
Employee [id=0, firstName=Hari krishna, lastName=Gurram]



Previous                                                 Next                                                 Home

No comments:

Post a Comment