XSD - child elements depending on attribute value

I am trying to create an XSD schema for the following XML:

<root>
  <!-- The actual file must contain one of the following constraints -->
  <constraint type="interval">
    <min>100</min>
    <max>200</max>
  </constraint>

  <constraint type="equals">
    <value>EOF</value>
  </constraint>
</root>

child elements of a constraint element depend on the value of the type attribute.

I successfully validated XML using an abstract type defining a type attribute and two extending types defining child elements. This would require me to decorate the XML with the xsi: type attribute, naming the actual extensible type:

  <constraint type="interval" xsi:type="intervalConstraintType">
    <min>100</min>
    <max>200</max>
  </constraint>

Unfortunately, I do not control the XML structure, and the new attributes will be hard to imagine.

Can this be done with XSD? Are there alternatives that are more suitable?

+3
source share
2 answers

, , , . xml , .

: , , , , XSD 1.0

0

type.

, XSD 1.1 . (untested)

<!-- ... -->
<xs:element name="constraint"> 
  <xs:complexType> 
     <xs:sequence> 
         <xs:element name="min" type="xs:decimal" minOccurs="0" maxOccurs="1" /> 
         <xs:element name="max" type="xs:decimal" minOccurs="0" maxOccurs="1" />
         <xs:element name="value" type="xs:string"minOccurs="0" maxOccurs="1" />
     </xs:sequence> 
     <xs:attribute name="type" type="contraintType" />

     <xs:assert test="

        if (@type eq 'equals')
        then (exist(value) and empty(min, max))
        else (exist(min) and exist(max) and empty(value))

     "/>

</xs:complexType> 
</xs:element>

<xs:simpleType name="contraintType">
    <xs:restriction base="xs:string">
        <xs:enumeration value="interval"/>
        <xs:enumeration value="equals"/>
    </xs:restriction>
</xs:simpleType>
0

All Articles