Search code examples
xmlxsdschema

XSD: Have a date element be either empty or meet restrictions


I have an XSD, and I need a date element to be either empty or be after a certain date (10/1/2015).

So, the following should be allowed:

<DDate></DDate>
<DDate>2015-10-10</DDate>

My XSD is defined as:

<xs:element name = "DDate" nillable="true" >
    <xs:simpleType>
        <xs:restriction base="xs:date">
            <xs:minInclusive value="2015-10-01"/>
        </xs:restriction>
    </xs:simpleType>
</xs:element>

This enforces that the date is correct, but does not allow the date to be empty. Any insight or advice would be appreciated.


Solution

  • Your definition already allows an empty DDate, except for one restriction, you must also specify xsi:nil="true", like so:

    <!-- ns decl. should go to the root element -->
    <DDate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="xsd-date-empty.xsd" 
        xsi:nil="true" />
    

    But, if with "allow empty", you mean that you want to allow whitespace, and/or empty nodes without the use of xsi:nil, there are many ways to do that. I would probably go with a union, like this:

    <xs:element name = "DDate" nillable="true" >
        <xs:simpleType>
            <xs:union>
                <xs:simpleType>
                    <xs:restriction base="xs:date">
                        <xs:minInclusive value="2015-10-01"/>
                    </xs:restriction>        
                </xs:simpleType>            
                <xs:simpleType>
                    <xs:restriction base="xs:string">
                        <xs:whiteSpace value="collapse" />
                        <xs:length value="0" />
                    </xs:restriction>        
                </xs:simpleType>            
            </xs:union>
        </xs:simpleType>
    </xs:element>
    

    Which means nothing more than allow either a:

    • date with minInclusive restrictions
    • string that is empty after whitespace is collapsed