Search code examples
xmlxsdxsd-validationxml-validation

How to define maxOccurs anywhere in element's scope in XML Schema?


I would like to know if there's a way how to define maxOccurs of content in abc element? It doesn't matter how many of content elements there are in a, b and c as long as there's no more than x number of occurrences in the whole abc. Thanks in advance!

<abc>
    <a>
        <content>AA</content>
        <content>AAA</content>
    </a>

    <b>
        <content>B</content>
    </b>

    <c>
        <content>CCC</content>
        <content>C</content>
    </c>
</abc>

Solution

  • XSD 1.0

    Not possible. Would have to be checked out-of-band wrt XSD.

    XSD 1.1

    Possible using xs:assert:

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
               vc:minVersion="1.1">
    
      <xs:element name="abc">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="a" type="HasContentType"/>
            <xs:element name="b" type="HasContentType"/>
            <xs:element name="c" type="HasContentType"/>
          </xs:sequence>
          <xs:assert test="count(*/content) &lt;= 5"/>
        </xs:complexType>
      </xs:element>
    
      <xs:complexType name="HasContentType">
        <xs:sequence>
          <xs:element name="content" type="xs:string" 
                      minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
      </xs:complexType>
    </xs:schema>
    

    Note: The above assertion constrains the total number of content element occurrences within child elements of abc. Should you want to constrain occurrences anywhere in the hierarchy beneath abc as your title suggests in saying anywhere in element's scope, you could instead use this assertion:

          <xs:assert test="count(.//content) &lt;= 5"/>