XSD - allow element type as integer OR empty

leanne picture leanne · Aug 18, 2011 · Viewed 39.9k times · Source

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"/>

Answer

Ahmad Hindash picture Ahmad Hindash · Nov 12, 2013

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.