I have an XML schema:
<xsd:element name="Person">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name" type="xsd:string" />
<xsd:element name="lat" type="xsd:double" minOccurs="0"/>
<xsd:element name="lon" type="xsd:double" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
And I have an XML message:
<Person>
<name>Fred</name>
</Person>
I use JAXB to auto-generate my classes (i.e. Person.java, etc).
So at run time I use JAXB to unmarshal the above XML message and get a Person object instance. When I do a p.getLat()
or p.getLon()
the return values are 0.0 even though the original XML didn t contain <lat>
or <lon>
elements.
What makes this worse is that 0.0, 0.0 is a valid latitude and longitude. It s rare for a person to be located there but that s beside the point!
An article on the IBM site suggested using an additional XML element as metadata to explicitly state whether the optional element exists or not. i.e.
<xsd:element name="hasLat" type="xsd:boolean"/>
<xsd:element name="hasLon" type="xsd:boolean"/>
So the XML message above would become:
<Person>
<name>Fred</name>
<hasLat>false</hasLat>
<hasLon>false</hasLon>
</Person>
This seems like an ugly hack. There must be a proper way with JAXB to check if the element existed so that I can trust the return value from my getLat()
, getLon()
?