Re: minOccurs dependent on other element value / xpath

Hi Sam,

>Is it possible to specify minOccurs dynamically; dependent on the value of an element in the schema instance?
>
Unfortuantely you can't express these kinds of co-occurence constraints 
using W3C XML Schema alone. If you don't mind the extra processing 
involved in embedding Schematron rules in your schema you can express 
this very easy. See below in the annotated schema:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
   <xs:element name="package">
      <xs:complexType>
         <xs:all>
            <xs:element name="header">
               <xs:complexType>
                  <xs:all>
                     <xs:element name="name" type="xs:string"/>
                     <xs:element name="isFinal" type="xs:boolean"/>
                  </xs:all>
               </xs:complexType>
            </xs:element>
            <xs:element name="plans" minOccurs="0">
               <!-- Add a Schematron rule to check the value of isFinal -->
               <xs:annotation>
                  <xs:appinfo>
                     <sch:pattern name="Check isFinal" xmlns:sch="http://www.ascc.net/xml/schematron">
                        <sch:rule context="plans">
                           <sch:assert test="count(plan) &gt;= ../header/isFinal">You must have at least one plan element if the value of isFinal is 1.</sch:assert>
                        </sch:rule>
                     </sch:pattern>
                  </xs:appinfo>
               </xs:annotation>
               <xs:complexType>
                  <xs:sequence>
                     <xs:element name="plan" type="xs:anyType" minOccurs="0" maxOccurs="unbounded"/>
                  </xs:sequence>
               </xs:complexType>
            </xs:element>
         </xs:all>
      </xs:complexType>
   </xs:element>
</xs:schema>

The above Schematron rule will check that the number of plan elements always is greater than or equal to the value of the isFinal element. Note: The above only works if isFinal has the value 0 or 1. If the value can be true or false as well the Schematron rule needs to be modified.

For more information about how to embedd Schematron rules in other XML Schema languages see [1].

Cheers,
/Eddie

[1] http://www.topologi.com/public/Schtrn_XSD/Embedded_Schematron.html

Received on Wednesday, 26 June 2002 20:00:18 UTC