Search code examples
xmlxsd

How to enforce one of two types for a single XSD element?


I have an xml element called "PRICE".

I want to allow in this field EITHER a number OR one of the enum values {MAX, MIN, UNAV}. Is this possible with XSD?

This snippet demonstrates what I want, however it is invalid:

       <xs:choice>
           <xs:element name="PRICE">
               <xs:simpleType>
                   <xs:restriction base="xs:string">
                       <xs:enumeration value="MAX"/>
                       <xs:enumeration value="MIN"/>
                       <xs:enumeration value="UNAV"/>
                   </xs:restriction>
               </xs:simpleType>
           </xs:element>
           <xs:element name="PRICE">
               <xs:simpleType>
                   <xs:restriction base="xs:float"/>
               </xs:simpleType>
           </xs:element>
       </xs:choice>

Solution

  • <xs:element name="Price">
        <xs:simpleType>
            <xs:union>
                <xs:simpleType>
                    <xs:restriction base="xs:string">
                        <xs:enumeration value="MAX"/>
                        <xs:enumeration value="MIN"/>
                        <xs:enumeration value="UNAV"/>
                    </xs:restriction>
                </xs:simpleType>
                <xs:simpleType>
                    <xs:restriction base="xs:float"/>
                </xs:simpleType>
            </xs:union>
        </xs:simpleType>
    </xs:element>