We have an xml file that looks as follows. Note that our application supports all 3 of these cases:
<quantities>
<quantity>8</quantity> <!-- case 1 -->
<quantity></quantity> <!-- case 2 -->
<quantity/> <!-- case 3 -->
</quantities>
We are now making an XML Schema for our customers to help them validate their files before they send them to our application.
<xs:element name="quantity" type="xs:double"/>
But the above XSD is too simple. It is a good validation for case 1, but it refuses case 2 and 3.
So, we tried to solve this using a custom type. A type that can be both a double but can also an empty string.
<xs:simpleType name="double-or-empty">
<xs:union memberTypes="xs:double">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value=""/>
</xs:restriction>
</xs:simpleType>
</xs:union>
</xs:simpleType>
<xs:element name="quantity" type="double-or-empty"/>
From a functional point, this is clearly an improvement, but it has its shortcomings. When we generate our java classes with java's xjc.exe
tool. Then java will use a String
to represent these fields. Which is very annoying. What we actually hoped for were (nullable) java.lang.Double
fields.
An idea that we played with: To make an xsd file that marks this field as nillable
.
<xs:element name="quantity" type="xs:double" nillable="true"/>
We learned that this still does not support case 2 and 3. This just adds 1 more case to it:
<quantities>
<quantity xs:nil="true"/>
</quantities>
Multiple sources indicate that the use of xs:nil
can break interoperability though. Then other sources claim that we should use a custom attribute e.g. <quantity null="true"/>
These kinds of ideas are useless anyway because they force us to change an XML format that we have been using for a long time.
So, is there a way to keep the original format, and to steer the XJC tool to use Doubles here?