Tuesday, July 12, 2016

Java : Object to Xml and vis versa

Object to Xml and vis versa


JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file. In this tutorial, we show you how to use JAXB to do following stuffs :
  1. Marshalling – Convert a Java object into a XML file.
  2. Unmarshalling – Convert XML content into a Java Object.

Required library : https://jaxb.java.net/latest/download.html

Marshalling

@XmlRootElement
public class Customer {
 String name;
 int age;
 int id;
 public String getName() {
  return name;
 }
 @XmlElement
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 @XmlElement
 public void setAge(int age) {
  this.age = age;
 }
}


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

   Customer customer = new Customer();
   customer.setName("John");
   customer.setAge(18);

   try {

  File file = new File("C:\\file.xml");
  JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
  Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

  // output pretty printed
  jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

  jaxbMarshaller.marshal(customer, file);
  jaxbMarshaller.marshal(customer, System.out);

       } catch (JAXBException e) {
  e.printStackTrace();
       }

 }
}
 Output:
<customer age="18">
    <name>John</name>
</customer> 

Unmarshalling

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

  try {

  File file = new File("C:\\file.xml");
  JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
  System.out.println(customer);

   } catch (JAXBException e) {
  e.printStackTrace();
   }

 }
} 
Customer [name=John, age=18] 

No comments:

Post a Comment