Saturday, August 29, 2009

Binding XML to Java Code with JiBX

I was looking for a simple, lightweight, fast xml-java binding solution. Tried few libraries like JAXB, XMLBean, JiBX, Castor and finally settled down with JiBX. JiBX is simple, it generates very few classes from a given schema and its fast! We can also write a binding.xml to map java to xml document. JiBX project site has great documentation if you want to get started with JiBX.
Lets go through the basic steps of generating java objects, doing jibx binding and marshal & unmarshal
  • download JiBX
  • set JIBX_HOME environment variable
  • generate java source from my_schema.xsd
java -cp $JIBX_HOME/lib/jibx-tools.jar org.jibx.schema.codegen.CodeGen -t source_dir my_schema.xsd
  • compile generated java source:- javac source_dir/**/*.java
  • jibx binding:- java -jar $JIBX_HOME/lib/jibx-bind.jar binding.xml
  • write sample code to marshal & unmarshal
java -cp $JIBX_HOME/lib/jibx-run.jar:$$JIBX_HOME/lib/xpp3.jar MyTestClass
Code in MyTestClass would look as below
IBindingFactory bfact = BindingDirectory.getFactory(MyAnyGenerated.class); IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); IMarshallingContext mctx = bfact.createMarshallingContext();
Object obj = uctx.unmarshalDocument(new FileInputStream("input.xml"), null); mctx.marshalDocument(obj, "UTF-8", null, new FileInputStream("output.xml"));
Compare to JAXB, JiBX generates very few classes from a given schema. We can also customize source code generation using custom.xml. JiBX generates a binding.xml which is used for JIBX binding. We can also write the binding.xml manually and bind existing value object to xml definition.  I had run a small test to compare marshal & unmarshal with JIBX, JAXB & XMLBean and found that JIBX is almost 2x faster than other two.

No comments: