Search code examples
xmlxsdxsd-validationxml-validation

How to allow one element or another choice of elements in XSD?


Suppose that I have a <scene> element which can contain the following elements:

  • <episode> and/or <season>
  • OR <part>

Some examples:

<scene>
  <part></part>
</scene>

Another example:

<scene>
 <episode></episode>
 <episode></episode>
 <season></season>
 </scene>

Another one:

<scene>
 <episode></episode>
 <season></season>
 <episode></episode>
 </scene>

So the idea here is allowing episodes and seasons in <scene> (with unbounded limits). And if these two elements (seasons and episodes) doesn't exist you can use <part> element inside <scene> with unbounded limits.

I'm trying to do this in XML Schema. I tried groups and complexContent without success. Any ideas?


Solution

  • Use compound xs:choice elements:

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    
      <xs:element name="scene">
        <xs:complexType>
          <xs:choice>
            <xs:element name="part" maxOccurs="unbounded"/>
            <xs:choice maxOccurs="unbounded">
              <xs:element name="episode"/>
              <xs:element name="season"/>
            </xs:choice>
          </xs:choice>
        </xs:complexType>
      </xs:element>
    
    </xs:schema>
    

    This says that scene can consist of either an unbounded number of part elements or an unbounded mix of episode and season elements.