Search code examples
xmlxsd

XML Schema with a combination of "choice" and "all"


I am trying to write an XSD that will validate XML where the following must be true:

An element (Parent) includes:

  • either "Choice1" OR "Choice2" elements
  • plus any or all of "Field1", "Field2", "Field2" (etc.)
  • The above fields can appear in any order

So, for example, valid XML would be:

<Parent>
  <Choice1>xxx</Choice1>
  <Field1>yyy</Field1>
  <Field2>yyy</Field2>
</Parent>

as would:

<Parent>
  <Field3>yyy</Field3>
  <Choice2>xxx</Choice2>
  <Field2>yyy</Field2>
</Parent>

Invalid would be:

<Parent>
  <Field3>yyy</Field3>
  <Field2>yyy</Field2>
</Parent>

I can't seem to nest xs:choice and xs:all as I would like to.


Solution

  • Yes, <xs:choice> cannot be inserted directly in <xs:all>. But you can achieve the same effect using a substitution group:

    <xs:element name="Parent">
      <xs:complexType>
        <xs:all>
          <xs:element ref="Choice" minOccurs="1"/>
    
          <xs:element name="Field1" type="xs:string"/>
          <xs:element name="Field2" type="xs:string"/>
        </xs:all>
      </xs:complexType>
    </xs:element>
    
    <xs:element name="Choice" abstract="true"/>
    <xs:element name="Choice1" substitutionGroup="Choice"> ... </xs:element>
    <xs:element name="Choice2" substitutionGroup="Choice"> ... </xs:element>