Tuesday, May 16, 2006

 

Using JAXB to generate XML schema from Java.

Recently I had attempted to start creating the XML schema for our tracking events by using the excellent oXygen, which you can use standalone or as a plugin for Eclipse. However, to be honest, I'm a beginner with XML schema, so even with code tips and code completion, I was finding it a bit of a struggle! However, it occured to me that I'm comfortable thinking in terms of objects, so I decided to give using JAXB a spin; specifically, to generate the schema from the Java (rather than the other way round!).

There are two features of Java 5 that prove useful straight away when working with JAXB; enums and annotations. In fact they really come into their own here! By default, JAXB maps an enum as a restricted set of strings (not as a restricted set of ints), so the mapping is very natural and of course you can do this very succinctly. If you only want the value of an element or attribute to be one of the values red, green or blue you can declare an enum thus; enum colour {red, green, blue};. Within JAXB you can use annotations to control how your Java gets mapped into schema. For example, if you want a property mapped as an attribute rather than an element, you can tag it with the annotation @XmlAttribute. You can put this on the field or on one of the appropriate accessors.



Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?