Saturday, 20 August 2016

JAXB: Convert Java object to XML

Following are the steps to convert java object to XML.

Step 1: Define model object using jaxb annotations.

Step 2: Define JAXBContext instance using model class Employee.

JAXBContext contextObj = JAXBContext.newInstance(Employee.class);

Step 3: Define Marshaller instance using the JAXBContext instance.

Marshaller marshallerObj = contextObj.createMarshaller();
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

Step 4: Now call marshal method on model object.
marshallerObj.marshal(emp1, System.out);


Following is the complete working application.
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;
 }

}

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

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

  Marshaller marshallerObj = contextObj.createMarshaller();
  marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

  Employee emp1 = new Employee();
  emp1.setId(1);
  emp1.setFirstName("Hari krishna");
  emp1.setLastName("Gurram");

  marshallerObj.marshal(emp1, System.out);
 }
}


Run above application, you will get following output.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <id>1</id>
    <firstName>Hari krishna</firstName>
    <lastName>Gurram</lastName>
</employee>


Annotations used

@XmlRootElement : Maps a class to an XML element. You can use this annotation on top of any class (or) enum.

@XmlType : Maps a class or an enum type to a XML Schema type. You can specify the order of element in the xml document.


Previous                                                 Next                                                 Home

No comments:

Post a Comment