Friday, October 3, 2014

On the "nillable" Attribute in XML Schema

In the XSD, you can define an element that is nillable:
  <xs:element name="abc" nillable="true" minOccurs="1" type="xs:string"/>
What does this "nillable" exactly mean?

If the element has to be there and you want it to be able to have null value, then you need to define nillable="true". And you can do the following in the XML file:

  <abc xsi:nil="true" />
The JAXB unmarshaller will create the object with abc=null.

Note that if you do <abc/> or <abc></abc>, then the element "abc" will have the value "". It is not null.

If the element does not need to be there, i.e, if minOccurs="0", then you do not need to have nillable="true". You can simply skip this element in the XML file. And the JAXB unmarshaller wil create an object with abc=null.

For element of type int, JAXB will create the Integer object for the element. So the effect will be the same as String when an int is nillable.

For JAXB marshaller, if the object has abc=null, then if in the schema minOccurs="0" for the element, no matter whether abc is nillable or not, the generated XML file will not have this element. But If minOccurs="1", then if nillable="false", the generated XML file will not have this element; if nillable="true", the generated XML file will be <abc xsi:nil="true" />.

No comments:

Post a Comment