Misenus
Misenus

Reputation: 139

Restricting XML element values based on other values in XSD

I am creating a schema in XSD 1.1 for crossword puzzles. One of my elements is <dimensions>. Example:

<xs:element name="dimensions">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:pattern value="\d+x\d+"/>
      </xs:restriction>
    </xs:simpleType>
 </xs:element>

The resulting XML would look like <dimensions>21x21</dimensions>, meaning that the puzzle grid is 21 squares by 21 squares.

I also have a <cell> element for every square in the puzzle. So for a puzzle with dimensions of 21x21, I would have 441 instances of <cell>. Each <cell> has a <coordinates> element describing its position in the grid:

<xs:element name="cell">  
    <xs:complexType>  
        <xs:sequence>
            <xs:element name="coordinates">
                <xs:simpleType>
                    <xs:restriction base="xs:string">
                        <xs:pattern value="\d+,\d+"/>
                    </xs:restriction>
                </xs:simpleType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>

So the position of the square in the bottom left corner of the grid would be represented by <coordinates>21,1</coordinates>, indicating that it is in the 21st row, 1st column.

I want to do the following:

  1. Require that there is one <cell> for every square, based on the <dimensions>. For instance, if the dimensions are 21x21, there must be 441 instances of <cell>--no more, no fewer.

  2. Require that the <coordinates> for each <cell> are unique and fall within the parameters of the <dimensions. In other words, for a 21x21 grid, each axis of the coordinates must be represented by a number between 1 and 21, and each of the 441 combinations can only be used once.

Upvotes: 2

Views: 148

Answers (2)

kjhughes
kjhughes

Reputation: 111491

Yes, assertions could be used, but an XML design change would be better...

The information you would place in dimensions is implied by the structure of your cell elements and can be derived automatically rather than allowed to be set arbitrarily and then have to be validated independently.

A similar argument applies to coordinates.

(Note also that even if you did wish to represent coordinates explicitly, it'd be better to use separate elements, or better yet, attributes, for each coordinate.)

Upvotes: 1

C. M. Sperberg-McQueen
C. M. Sperberg-McQueen

Reputation: 25034

You will need XSD 1.1; use an assertion. Or you will need to parameterize your schema (and probably reorganize your XML a bit) to enforce the constraint in a different way (e.g. by having the schema require exactly 21 rows, each with exactly 21 cells).

Upvotes: 1

Related Questions