sergiolopes
sergiolopes

Reputation: 1

XML Schema: limiting number of occurrences based on child elements

I have an element myCoupon with a sequence of curatedCoupon elements. I know I can restrict the number of occurrences by adding a maxOccurs attribute. I'd like, however, to restrict its number based on the isCouponActive element (say I want to only allow 5 active coupons). Is this achievable?

  <xs:complexType name="curatedCoupon">
    <xs:sequence>
      <xs:element name="isCouponActive" type="xs:boolean" default="false" minOccurs="0">
    </xs:sequence>      
  </xs:complexType>  

  <xs:element name="myCoupon">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="curatedCoupon" type="sbcc:curatedCoupon" minOccurs="0" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>

Upvotes: 0

Views: 1420

Answers (1)

Octavian
Octavian

Reputation: 444

You can do this by using an assertion constraint from XML Schema 1.1. On the 'myCoupon' element you can add an 'assert' like this:

<xs:element name="myCoupon">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="curatedCoupon" type="curatedCoupon" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
        <xs:assert test="count(curatedCoupon/isCouponActive[text()='true']) &lt;= 5"/>
    </xs:complexType>
</xs:element>

Upvotes: 1

Related Questions