Saturday, March 5, 2011

JAXB using castor framework
JAXB:Java API for XML binding.
JAXB allows to map the java fields to XML tags i.e binding the java fields to the corresponding XML tags.Using JAXB we can perform a)Marshalling and b)UnMarshalling
a)Marshalling:It is the process of converting java object graph to XML document.This is also called XMLSerialization.
b)UnMarshalling:It is the process of converting the XML document to Java Object graph.This is also called as XMLDeserialization

Required Jars:
1)Xerces 2)castor-1.3.1-ddlgen, castor-1.3.1-xml,castor-1.3.1-xml-schema,castor-1.3.1,castor-1.3.1-codegen,castor-1.3.1-core.

1)Create a project JAXBApp
1)Write a XSD(Schema document) file
2)Add the jar files to build path.
3)Create a class as below and run it for generating the java code.
package com.keely.jaxb.test;
import org.exolab.castor.builder.SourceGenerator;
public class Generator {
public static void main(String[] args) {

String[] arg = { "-i", "Customers.xsd", "-package", "com.tcs.castor" };
SourceGenerator generator = new SourceGenerator();
"-i" denotes the inputfile in our case the schema definition file
"-package" denotes the package under which the generated java code should fall into.
4)Now you can see generated classes under the package.Which consists of the setters and getters along with the code for marshal and unmarshal.

public void marshal(final out) throws org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
org.exolab.castor.xml.Marshaller.marshal(this, out);

public static com.tcs.castor.Customer unmarshal(final reader) throws
return (com.tcs.castor.Customer) org.exolab.castor.xml.Unmarshaller.unmarshal(com.tcs.castor.Customer.class, reader);

5)Copy the generated classes to source folder
6)Create a package called com.keely.jaxb.test with a class called and all the setters
7)Invoke the marshal method for creating the XML file as below.
Address address = new Address();
Customer customer = new Customer();

try {
customer.marshal(new FileWriter("Customers.xml"));
} catch (MarshalException e) {
// TODO Auto-generated catch block
8)This will generate the XML file "Customers.xml".
This process is called XMLSerialization
9)For XMLDeserialization:
Customers customers = new Customers();
try {
customers.unmarshal(new FileReader("Customers.xml"));
} catch (MarshalException e) {
// TODO Auto-generated catch block

No comments:

Post a Comment