The UrBlog

John's Ramblings about Software Development

Grails Script to Generate JAXB Classes

I think Groovy’s MarkupBuilder is great and I use it often. Sometimes though, I need to generate a complex XML document that conforms to an XSD. MarkupBuilder often leads to markup and business logic being mixed together much like HTML and Java code gets mixed in complex JSP pages. In cases like this, I like to use JAXB instead. I can generate classes from the XSD, load up an object model and let JAXB generate the markup.

It’s fairly easy to create a script to handle generating the JAXB classes for you. JAXB comes with a handy Ant task that takes your XSD and generates classes. The trick is passing the build classpath to the task. There is a “grailsSettings” variable available in scripts that contains BuildSettings. We can get the list of build dependencies files from this class to generate the classpath. Here is a simple example that takes the Microsoft books.xsd in the etc/schema directory and generates the code to the src/java directory:

UPDATE: Sometimes having the JAXB jars on your path can cause problems with your application. In those cases, you call the generation class directly:

Comments