Wednesday, 18 April 2012

JAXBElement and generateElementProperty

This had me perplexed for a while.

http://docs.oracle.com/cd/E19879-01/820-1072/ahiid/index.html

So, if you have for example a  name attribute which is a String and has minOccurs="0" nillable="true" for its schema element then there are 2 representations for "no value":

<person>
<name xsi:nil="true"/>
<age>21</age>
</person>

and:

<person>
<age>21</age>
</person>

Note that an empty String element is not the same:


<person>
<name/>
<age>21</age>
</person>

This can be interpreted as an empty String, "", rather than nil.


With this definition its not possible to marshal that in a way that does't lose information if you go direct to String, because you have to pick a representation when you unmarshal.

That is if you perform the marshalling activities xml -> String -> xml you have to pick which representation of nil to use in the final XML, and you have no information to allow you to determine which representation you came from.  So its possible they may end up different.

That's not good.  So JAXB doesn't do that by default.  Instead it wraps elements like this in JAXBElement rather than String so its xml -> JAXBElement -> xml, and the representation is preserved.

Said another way, you can avoid using JAXBElement if you pick the representation of nil you want for XML, by having minOccurs="0", nillable="false" for example.

Or, you can tell JAXB how to do it when you do wsdl2java by providing a binding file that contains generateElementProperty="false".

No comments:

Post a Comment