1

This is related to 37071177 but not quite the same.

Can I have a container with an attribute like:

<question type="select">
  <text>This is the text</text>
  <selection points="1">This is a choice</selection>
  <selection points="20">This is a different choice</selection>
</question>

where the selections are ONLY present if the parent @type attribute's value is "select" but not if it is "yes/no" or something else? I thought I could do this with an <xs:assert> but you can't put an assert there...

I found lots of examples on using co-constraints to restrict the presence of one attribute based on the presence or value of another, but not any to restrict the presence of an element (or maybe maxOccurs) based on an attribute value.

<!-- this is a question - it might have one or more selections depending on its type -->
<xs:complexType name="questionType">
  <xs:sequence>
    <xs:element name="topic" maxOccurs="1" minOccurs="1" type="xs:string" />
    <xs:element name="text" maxOccurs="1" minOccurs="1"></xs:element>
    <xs:element name="selection" maxOccurs="unbounded" minOccurs="0" type="selectionType" />
  </xs:sequence>
    <xs:attribute name="id" type="xs:string" use="required" />
    <xs:attribute name="type" use="required">
      <xs:simpleType>
        <xs:restriction base="xs:string">
        <xs:enumeration value="yesno" />
        <xs:enumeration value="select" />
      </xs:restriction>
    </xs:simpleType>
  </xs:attribute>
</xs:complexType>

<!-- if the type of the question is 'selection' it may have one or more of these -->
<xs:complexType name="selectionType">
  <xs:simpleContent>
    <xs:extension base="xs:string">
      <xs:attribute name="points" type="xs:int" use="required" />
    </xs:extension>
  </xs:simpleContent>
</xs:complexType>
wz2b
  • 1,017
  • 7
  • 24
  • 1
    The prototypical way to vary type per an attribute in XSD is via Conditional Type Assignment. See duplicate link for an example. You could also express the constraint via assertions as you predicted, but you neglected to show what you've tried. ("...but you can't put an assert there..." is too vague to be corrected productively.) Finally, it's generally better design to migrate type attribute values into element names: `` and `` and ``; then you don't even need XSD 1.1. – kjhughes Sep 09 '20 at 02:53
  • 1
    I understand it wasn't a great design choice the way I did it - I changed it as you suggested. Thank you! – wz2b Sep 09 '20 at 14:15

0 Answers0