Search code examples
xmlxsdcomplextype

Or statement in complex type in xmlschema


How can I define in XMLSchema this pattern of element ?
<port num="80"/>
<port min="80" max="443"\>
because port must be defined by an attribute num or a range.


Solution

  • You can achieve that if your parser supports W3C XSD 1.1:

    <xs:element name="port" type="portType" />
    <xs:complexType name="portType">
        <xs:attribute name="min" type="xs:integer" use="optional"/>
        <xs:attribute name="max" type="xs:integer" use="optional"/>
        <xs:attribute name="num" type="xs:integer" use="optional"/>
        <xs:assert test="@num or (@max and @min)" />
    </xs:complexType>
    

    If your parser doesn't support XSD 1.1, you can use XSD 1.0 + Schematron, where you place your assertions inside xs:annotation/xs:appinfo and use XSLT or some external tools to validate them. In your case, it might be simpler just to check those assertions in the language that is running your parser after the XSD validation.