Program to demonstrate conversion of a Java Object to Xml using JAXB API and Annotations through a Java program
Steps to convert Object to Xml :
1. Creating a POJO class :
2. Create a conversion class :
3. Output of the program - XML file created as "Customer.xml"
Steps to convert Object to Xml :
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.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBObjectToXml {
public static void main(String[] args) throws IOException {
Customer customer = new Customer();
customer.setId(1);
customer.setFirstName("Jonty");
customer.setLastName("Magicman");
customer.setEmail("jontymagicman@hubberspot.com");
try {
JAXBContext context = JAXBContext.newInstance(Customer.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer,
new BufferedWriter(new FileWriter("Customer.xml")));
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
3. Output of the program - XML file created as "Customer.xml"
