Program to demonstrate conversion of a Xml to Java Object using JAXB API and Annotations through a Java program
Steps to convert Xml to Object :
1. Creating a POJO class :
2. Create a conversion class :
3. Input of the program - XML file as "Customer.xml"
4. Output of the program :
Steps to convert Xml to Object :
1. Creating a POJO class :
package com.hubberspot.examples;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
private Integer id;
private String firstName;
private String lastName;
private String email;
public Customer(){
}
public Integer getId() {
return id;
}
@XmlAttribute
public void setId(Integer id) {
this.id = id;
}
@XmlElement
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@XmlElement
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@XmlElement
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2. Create a conversion class :
package com.hubberspot.examples;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class JAXBXmlToObject {
public static void main(String[] args) {
try {
JAXBContext context = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(
new File("Customer.xml"));
System.out.println("Customer Id : "
+ customer.getId());
System.out.println("Customer FirstName : "
+ customer.getFirstName());
System.out.println("Customer LastName : "
+ customer.getLastName());
System.out.println("Customer Email : "
+ customer.getEmail());
}
catch (JAXBException e) {
e.printStackTrace();
}
}
}
3. Input of the program - XML file as "Customer.xml"
4. Output of the program :

