Search code examples
xmlxsd

XSD make attribute nullable


When creating the XML the attribute wait may not always contain a value. How can I edit the schema so it allows the attribute wait to contain either a number or no value?

<xs:complexType name="CommandType">
        <xs:simpleContent>
            <xs:extension base="xs:string">
                <xs:attribute type="xs:string" name="exe" use="required" />
                <xs:attribute type="xs:string" name="args" use="required" />
                <xs:attribute type="xs:int" name="wait" use="required" />
                <xs:attribute type="xs:string" name="expectedOutput" use="required" />
                <xs:attribute type="xs:string" name="toVariable" use="required" />
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>

I have tried doing both these nillable="true" xsi:nil="true" but they don't work. When I tried to validate the XSD I got errors.


Solution

  • "nillable" only works for elements, not for attributes - and even then it's not very useful because if the element is empty you have to add xsi:nil="true", which is completely redundant.

    Either (a) define a type that's a union of xs:integer and a zero-length string, as suggested by IMSoP, or (b) define a list type with item type integer, minLength 0, maxLength 1. I prefer the latter solution as it plays better with schema-aware XSLT and XQuery.

    For example:

    <xs:simpleType name="list-of-int">
       <xs:list itemType="xs:integer"/>
    </xs:simpleType> 
     
    <xs:simpleType name="optionalInt">
       <xs:restriction base="list-of-int">
          <xs:minLength value="0"/>
          <xs:maxLength value="1"/>
       </xs:restriction>
    </xs:simpleType>