I am receiving XML from a server whose schema specifies nearly every element as:
<xs:element name="myStringElementName" type="xs:string" nillable="true" minOccurs="0"/>
<xs:element name="myIntElementName" type="xs:int" nillable="true" minOccurs="0"/>
I’m trying to find a clean way to convert every element that I receive that is marked as xsi:nil="true" to a null when it is unmarshalled into a JAXB object. So something like this:
<myIntElementName xsi:nil="true" />
Should result in my JAXB object having a myIntElementName property with a value of null, rather than a JAXBElement object with a nil property set to true (or anything along those lines). I don’t have any control over the system that is sending me the XML that uses the nillable attribute, so I need to convert this on my end when I receive it.
@XmlElement(nillable=true)
You just need to specify
@XmlElement(nillable=true)on your field/property to get this behaviour:Generating From an XML Schema
Below I’ll demonstrate how to generate this mapping if you are staring from an XML schema.
XML Schema (schema.xsd)
Why you get a property of type
JAXBElementA property of type
JAXBElementis generated in your model because you have a nillable element this isminOccurs="0". The use ofJAXBElementallows the model to differentiate between an missing element (property is null) and the presence of the element withnil="true"(JAXBElement with nil flag set).External Binding File (binding.xml)
An external binding file can be specified to tell the JAXB implementation not to generate any properties of type
JAXBElement. Note this will make it impossible for JAXB to round trip all XML documents.XJC Call
Below is an example of how to leverage an external binding file from the XJC Call
Generated Model (Foo)
The generated model will look something like the following:
For More Information