Tuesday, November 27, 2012

Get started with JAXB

If you are a beginner for JAXB. Here is the simple example will help you to get started.

All you need to have is JDK environment. This comes along with JAXB implementation.

This particular example is based upon the customer data, which deals with marshaling and unmarshaling.

Work flow:
1. Define your customer class, and identify the elements and attributes as part of  it.

Customer.java


import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@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 int getId() {
return id;
}

@XmlAttribute
public void setId(int id) {
this.id = id;
}

}

2. Using JAXB Context do the marshaling.

CustomerJAXBMarshal.java

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

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

Customer customer = new Customer();
customer.setId(100);
customer.setName("Raj");
customer.setAge(20);

try {

File file = new File("C:\\Customer.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 on console:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
    <age>20</age>
    <name>Raj</name>
</customer>


3.  Unmarshal the Customer XML file to build the Customer run time object.

CustomerJAXBUnmarshal.java

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

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

try {

File file = new File("C:\\Customer.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();
}

}
}

Output on console:
Customer@1feca64



No comments:

Post a Comment