Tuesday, February 07, 2012

Spring and JiBX

When I first heard about JiBX I could not have know that this would be one of the greatest tools for processing XML files that I would use.

It all started when we had a project where a speed and flexibility of XML processing was required and we started of with using XMLBeans as this was already packed with Weblogic server. A little did we know that JiBX will beat XMLBeans in almost every aspect. We had about 100 schemas to process with average of 100 tags and tons of imports. XMLBeans compiled 1 schema for almost a minute and created file that was more that 1MB. JiBX compiled all schemas in a little more than a minute. One jar file was packed at 10 times less space than XMLBeans. When thinking about loading all those files into memory, you will end up using quite a bit of PermGen space. Don't get me wrong, I still use XMLBeans today for some tasks, but I believe that if you can choose a tool for XML processing, choose JiBX and you will not be sorry.

To start off, you would create an XML file (do not forget namespace as this will be used as a package in the jar file) as this is easier than creating XSD from scratch. After that, you can use XMLBeans inst2xsd to convert it to XSD.

..\inst2xsd -design rd -enumerations never -outPrefix test test.xml

When choosing design, you might want to experiment with options. Russian Doll Design is simplest one, so you might want to start with that until you understand how types and elements are used not just in regards to XSD but also how is this going to be reflected in your classes. Turn off enumerations as this will mess up the file. You can add them later manually.

At this point you can copy this to your JiBX directory and create a custom XML (using <custom> - optional) if you have to specifically process some elements and leave others out (cool feature if you need to keep the size of your jar file down, especially if a lot of types and imports are used). One of the advantages of the JiBX is it's high speed and adaptability. For example, if you wanted to pass some custom date in XML, you would need to use string type. But not with JiBX. You can specify how you want to serialize/deserialize the elements when binding them. This is generated by either using predefined classes or creating your own  (you can do that by extending org.jibx.runtime.JodaConvert and then creating your Utility class). A very handy thing to use to adapt to different environments and clients.

JiBX comes with both ANT and MAVEN support and it is very easy to setup. You can find a lot of examples on JiBX site.

When integrating with Spring, it is extremely simple and you can use it to custom build your beans, web services or anything that deals with XML. Spring comes with a lot of support for different Object/XML Mapping and you can read about it here.