Re: Restricting values for a group of elements

Hi Maggie,

> I am still trying to learn the basics of XML Schema, and I haven't been able
> to work out whether there is a way of restricting a group of values in an
> instance document i.e. I would like, say, elements a, b, and c to have a min
> value of 0 and max value of 15, but the total sum of a, b and c cannot
> exceed 30.  Is this possible at all?

Unfortunately there is no way of doing this with this version of W3C XML Schema.
These kind of co-constraints are on the agenda for the next version whenever
that will happen. In the mean time my favourite way of dealing with these types
of problems is to embedd a Schematron rule that applies the constraints you
can't do with the W3C XML Schema. Here is an example of what that would look
like in your case:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified" attributeFormDefault="unqualified">
 <xs:element name="Root">
  <xs:annotation>
   <xs:appinfo>
    <pattern name="Sum of child elements"
xmlns="http://www.ascc.net/xml/schematron">
     <rule context="Root">
      <assert test="sum(*) &lt;= 30">The sum of the child elements must be less
than or equal to 30.</assert>
     </rule>
    </pattern>
   </xs:appinfo>
  </xs:annotation>
  <xs:complexType>
   <xs:sequence>
    <xs:element name="a" type="myInteger"/>
    <xs:element name="b" type="myInteger"/>
    <xs:element name="c" type="myInteger"/>
   </xs:sequence>
  </xs:complexType>
 </xs:element>
 <xs:simpleType name="myInteger">
  <xs:restriction base="xs:integer">
   <xs:minInclusive value="0"/>
   <xs:maxInclusive value="15"/>
  </xs:restriction>
 </xs:simpleType>
</xs:schema>

This would validate the following instance document:

<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="E:\Work\XMLSchema\XML-DEV\Schtrn+W3C\sum_lt_30.xsd">

 <a>10</a>
 <b>10</b>
 <c>10</c>
</Root>

by this would be invalid:

<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="E:\Work\XMLSchema\XML-DEV\Schtrn+W3C\sum_lt_30.xsd">

 <a>10</a>
 <b>10</b>
 <c>12</c>
</Root>


The Schematron Validator available from Topologi [1] can validate a W3C XML
Schema with embedded Schematron information. For more information about
Schematron see [2] and more information about extending W3C XML Schema see [3].

Cheers,
/Eddie

[1] www.topologi.com
[2] http://www.ascc.net/xml/resource/schematron/
[3] http://www.xfront.com/BestPracticesHomepage.html

Received on Thursday, 6 September 2001 19:42:41 UTC