XML to Java code generation

 XML to Java code generation using CASTOR and JAXB

This tutorial explains the code generation from xml to java by using Castor and JAXB in brief. 

Procedure

  1.  Generate XSD from XML using CASTOR
  2.  Generate Java objects from XSD JAXB. http://castor.codehaus.org/
 Each of the steps in detail below.

XSD Generation

  
There are lot of tools available to generate XSD from XML including a few online tools. CASTOR is one such tool can be used to generate XSD form XML.

Castor is the Open Source data binding framework for Java. Mainly it consists of two features Castor XML and Castor JDO.

Download and install castor from http://castor.codehaus.org/

The Castor JARs, docs, DTDs, command line tools, and examples can be downloaded from http://dist.codehaus.org/castor/1.3.3-RC1/castor-1.3.3-RC1.tgz

 
 

XML Instance to Schema



Follow the below steps to generate Schema from XML.
  1. Open command prompt
  2. Java_home should point to java install directory
  3. Set castor_home to castor install directory.
  4. Set classpath to include all the castor dependency jars as below. 


Castor_home>set classpath=%classpath%;.;castor-1.3-anttasks.jar;castor-1.3-codegen.jar;castor-1.3-core.jar;castor-1.3-ddlgen.jar;castor-1.3-jdo.jar;castor-1.3-xml-schema.jar;castor-1.3-xml.jar;castor-1.3.jar;jta1.0.1.jar;commons-logging-api-1.0.4.jar

 
 
    5. Use XMLInstance2Schema class to generate Schema

Sample.xml

 


<sample attr1="ACCT" attr2="2001" id="978"/>


 XSD generation

 
 

Castor_home > java org.exolab.castor.xml.schema.util.XMLInstance2Schema gens\sample.xml sample_schema.xsd

 

Gendrated XSD 

 
The following xml will be generated after executing the above command.



<?xml version="1.0" encoding="UTF-8" ?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <element name="Sample">
    <complexType>
     <sequence />
       <attribute name="attr1" type="string" />
       <attribute name="attr2" type="integer" />
      <attribute name="id" type="integer" />
   </complexType>
</element>
</schema>

 

JAXB

 
 
The Java Architecture for XML Binding API (JAXB) makes it easy to access XML documents from applications written in the Java programming language. JAXB is bundled with java version 6 onwards.

Java Architecture for XML Binding (JAXB) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. In other words, JAXB allows storing and retrieving data in memory in any XML format, without the need to implement a specific set of XML loading and saving routines for the program's class structure

JAXB is a part of the Java SE platform and one of the APIs in the Java EE platform, and is part of the Java Web Services Development Pack (JWSDP). It is also one of the foundations for WSIT. JAXB is part of SE version 1.6.
 

XSD to java


Use the following steps to generate java objects from XSD
  1. Open command prompt
  2. Set java_home
  3. Use the JAXB schema compiler, xjc command to generate JAXB-annotated Java classes. The schema compiler is located in the java installation directory.
  4. The schema compiler produces a set of packages containing Java source files and JAXB property files depending on the binding options used for compilation

Command> xjc -no-header -npa schemas\sample_schema.xsd -p com.ssc.xml -d generated

-npa : suppress generation of package level annotations

-no-header :  suppress generation of a file header with timestamp

-p : Package name for generated source files

-d : output folder name
 

This generates two files in the output directory, one is the ObjectFactory and another is the actual java object. The ObjectFactory can be used to programmatically construct the java object during runtime.

The generated java class will look like below.
 

Generated Java Class 

 
 
 

The xml requests from client can be marshaled and unmarshalled as below.
 

JAXB Context

 

The JAXBContext class provides the client's entry point to the JAXB API. It provides an abstraction for managing the XML/Java binding information necessary to implement the JAXB binding framework operations: unmarshal, marshal and validate.
 

The JAXBContext instance is initialized from a list of colon separated Java package names 
 

JAXBContext class 


 
 
private  static JAXBContext initContext() {    
       try {     
           return JAXBContext.newInstance(Sample.class);
       } catch (JAXBException e) {
           logger.fatal("Context not initialized :" + e);
       }
       return null;
    }
 


 

Unmarshalling XML to Java  

 
       final StringReader xmlReader = new StringReader(xmlString);
       final StreamSource xmlSource = new StreamSource(xmlReader);
 
       Unmarshaller u = _CONTEXT.createUnmarshaller();
       Sample sample= (Sample) u.unmarshal(xmlSource);
 

 

Marshalling Java to XML  

 
     _CONTEXT.createMarshaller().marshal(sample, handler);
 

For more reading,

http://java.sun.com/webservices/jaxb/index.jsp

 






Comments

  1. Better and faster way to obtain JAXBContext

    public class XmlBidningContext {

    private static final JAXBContext _CONTEXT = initContext();

    private static JAXBContext initContext()
    {
    try
    {
    //Register all the classes here at once
    return JAXBContext.newInstance(new Class[] { A.class, B.class, C.class});
    }
    catch (JAXBException localJAXBException)
    {
    logger.fatal("Context not initialized :" + localJAXBException);
    }
    return null;
    }

    public static JAXBContext getBindingContext()
    {
    return _CONTEXT;
    }
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Log4j multiple WAR files in single EAR configuration

Java NIO2 - Watching a directory for changes. FileWatcherService.

Ubuntu Add programs to launcher (Desktop)