XSD make attribute nullable

2020-08-02 06:30发布

问题:

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.

回答1:

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



回答2:

There may be an easier way, but perhaps you could create a custom type that was either an empty string or conformed to the definition of xs:int using a union type:

<xs:simpleType name="emptyString">
    <xs:restriction base="xs:string">
        <xs:length value="0" />
    </xs:restriction>
</xs:simpleType>
<xs:simpleType name="intOrEmpty">
    <xs:union memberTypes="xs:int emptyString" />
</xs:simpleType>

Incidentally, it's worth remembering that the xs:string type includes empty strings, so if, say, the exe attribute should always have a non-empty value, you need a nonEmptyString type (using a minLength restriction) as well as marking it as required. I know that's caught me out in the past.



标签: xml xsd