Pages

Saturday, March 5, 2011

JAXB using castor framework

http://castor.org/xml-mapping.html
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.

Steps:
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();
generator.main(arg);
}
}
"-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 java.io.Writer 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 java.io.Reader reader) throws
org.exolab.castor.xml.MarshalException,org.exolab.castor.xml.ValidationException
{
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 MarshalXMLGenerator.java and all the setters
7)Invoke the marshal method for creating the XML file as below.
Address address = new Address();
address.setCity("Banglore");
address.setPhone("09880614099");
address.setState("Karnataka");
address.setStreet("Marathalli");
Customer customer = new Customer();
customer.setCid("889");
customer.setCname("dileepkeely");
customer.setEmail("dileepkeely@gmail.com");
customer.addAddress(address);

try {
customer.marshal(new FileWriter("Customers.xml"));
} catch (MarshalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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
e.printStackTrace();
}

No comments:

Post a Comment