Thursday, October 03, 2013

JAXB namespace configuration

In this blog post I would like to demonstrate how to configure a namespace in the XML messages used by REST endpoints. If you would rather jump right to a working example, have a look on my github account. Let's consider the following example message, where widgets can have different type of resources.

In the above example all XML elements belong to the "" namespace. This simple widget configuration message could have the following XSD:

In order to generate and consume these type of messages we create our model WidgetConfig and WidgetConfigRef.

With the namespace attribute of @XmlRootElement, @XmlElementWrapper and @XmlElement we configure the namespace on all XML elements found in the XSD. Note the use of @XmlElementWrapper, which is used to produce a wrapper XML element around resource elements. In order to set the namespace prefix (in this case "bb") we need the following:

Next we use Spring's excellent Object/XML Mapping support by defining a marshaller/unmarshaller as shown below:

And we are ready. A working example you can find on my github account. Note, if you are still using Java 6, you need to update the JAXB implementation by including the following dependencies. Otherwise the namespace prefixes will not be set. The JAXB implementation in Java 7 hasn't got this issue.