I need to be able to set a simple element type as an integer but allow it to also be empty. This example sends an error if its empty and a blank field is not an integer. How can I get round this?
<xsd:element name="weight" type="xsd:integer"/>
What you have to do is assign restrictions on the same element plus make a union on them such as the following example:
<xs:element name="job_code">
<xs:simpleType>
<xs:union>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:length value="0"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType>
<xs:restriction base='xs:integer' />
</xs:simpleType>
</xs:union>
</xs:simpleType>
</xs:element>
By using this restriction, you tell the xml validation to allow any integer value and allowing the element if it is empty.
We can achieve this by making a SimpleType
<xs:simpleType name="NullOrInteger">
<xs:restriction base="xs:string">
<xs:pattern value="\d*|\s{0}" />
</xs:restriction>
</xs:simpleType>
Add NullOrInteger as the type where you want restriction for an integer or null value.
for example:
<xs:element name="null_or_int" type="NullOrInteger" />
You need to set the "nillable" attribute as true:
<xsd:element name="weight" type="xsd:integer" nillable="true"/>
See the XML Schema Primer.
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) -->
<products xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<product>
<weight xsi:nil="true"/>
</product>
</products>
Try the above, should work; most likely you forgot to add the xsi:nil attribute. Also, make sure that the weight element has no character as children (a white space would still not be acceptable). If you do have to pass some characters instead of an integer, than you have to define a union type to allow for both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With