Saturday, May 16, 2009

JAXB -Xml/Java Mapping

After looking at many options which helped me convert java classes into xml and vice versa, i found this JAXB very exciting.The Java Architecture
for XML Binding provides a powerful and practical way of working with XML content from within Java applications. The newly released JAXB 2.0 offers
many new features, including full support of all XML Schema features, significantly fewer generated classes, generated classes that are easier to
manipulate, and a more flexible validation mechanism.

JAXB prerequisites

To get started with JAXB 2.0 you need:

1 Java Platform, Standard Edition 5: JAXB 2.0 relies heavily on features of Java SE 5, such as annotations and generics
2. An implementation of JAXB 2.0

I chose this implementation -

To start with the JAXb we first need to generate java classes using the xsd.This can be easily done ussing the xjc compiler

syntax : $xjc .xsd -p -d

Once this command are exceuted the classes are generated in teh given package.These can be used to marshel and unmarshel the xml quite easily.

First we create a JAXBContext

JAXBContext jaxbContext = JAXBContext.newInstance("package.of.the.generated.classes");

Then carete a unmarsheller using the context

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

Use the unmarshellor to get the data objects for the xml

DataObj data = (DataObj) unmarshaller.unmarshal(url);

url is URL which returns the xml response.Also xml can be given from a file directly

this data object can ve used to access all other valuse presnt in the xml response.

Ref :

No comments:

Free Domain Names @!