JAX-B API provides
Steps to convert java object into XML document.
SOURCE:
SOURCE:
OUTPUT:
javax.xml.bind.Unmarshaller interface, It is used to un marshal(read) the xml document into Java Objects.
In this example, we are going to discuss about how to read contents from xml into java objects using JAX-B.
Steps to convert java object into 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
Employee.xmlCreate Employee POJO class25 IT Jhon klazck
SOURCE:
Employee.java
package com.becbe.jaxb.ch1;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Employee {
private int employeeId;
private String employeeName;
private int age;
private String dept;
/**
* @return the employeeId
*/
@XmlAttribute
public int getEmployeeId() {
return employeeId;
}
/**
* @param employeeId the employeeId to set
*/
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
/**
* @return the employeeName
*/
@XmlElement
public String getEmployeeName() {
return employeeName;
}
/**
* @param employeeName the employeeName to set
*/
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
/**
* @return the age
*/
@XmlElement
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the dept
*/
@XmlElement
public String getDept() {
return dept;
}
/**
* @param dept the dept to set
*/
public void setDept(String dept) {
this.dept = dept;
}
}
SOURCE:
XmlToObject.java
/**
*
*/
package com.becbe.jaxb.ch1;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
/**
* @author BECBE
*
*/
public class XmlToObject {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File xmlDocFile = new File("d:\\Employee.xml");
//Create JAX-B instance
JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
//Create UnMarshaller Instance
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
//Un marshalling the xml document to Employee pojo
Employee employee=(Employee) unmarshaller.unmarshal(xmlDocFile);
System.out.println("Name : "+employee.getEmployeeName());
System.out.println("Id : "+employee.getEmployeeId());
System.out.println("Age : "+employee.getAge());
System.out.println("Department : "+employee.getDept());
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT:
Name : Jhon klazck Id : 23456 Age : 25 Department : IT
Nice Article!!!!
ReplyDelete