Using W3C XML Schema - Part 2
by Eric van der Vlist
|
Pages: 1, 2, 3, 4, 5
Constraints
|
Table of Contents |
|
Content Types |
W3C XML Schema provides several flexible XPath-based features for
describing uniqueness constraints and corresponding references constraints.
The first of these, a simple uniqueness declaration, is declared with the
xsd:unique element. The following declaration, within the
context of our book document, indicates that the character name must
be unique.
<xsd:unique name="charNameMustBeUnique"> <xsd:selector xpath="character"/> <xsd:field xpath="name"/> </xsd:unique>
This location of the xsd:unique element in the schema gives
the context node in which the constraint holds. By inserting
xsd:unique under our book element, we specify that the
character has to be unique in the context of a book only.
The two XPaths defined in the uniqueness constraint are evaluated
relative to the context node. The first of these paths is defined by the
selector element. The purpose is to define the element which
has the uniqueness constraint -- the node to which the selector points must
be an element node.
The second path, specified in the xsd:field element. is
evaluated relative to the element identified by the
xsd:selector and can be an element or an attribute node. This
is the node whose value will be checked for uniqueness. Uniqueness over a
combination of several values can be specified by adding other
xsd:field elements within xsd:unique.
Keys
The second constraint construct, xsd:key, is similar to
xsd:unique, except that the value specified as unique can be
used as a key. This means that it has to be non-null, and that it can
be referenced. To use the
character name as a key, we can replace the xsd:unique by
xsd:key.
<xsd:key name="charNameIsKey"> <xsd:selector xpath="character"/> <xsd:field xpath="name"/> </xsd:key>
The third construct, xsd:keyref, allows us to define a
reference to a key. To show its usage, we introduce the
friend-of element, to be used against characters.
<character>
<name>Snoopy</name>
<friend-of>Peppermint Patty</friend-of>
<since>1950-10-04</since>
<qualification>
extroverted beagle
</qualification>
</character>
To indicate that friend-of needs to refer to a character
from the same book, we write, at the same level as we defined our key
constraint, the following:
<xsd:keyref name="friendOfIsCharRef" refer="charNameIsKey"> <xsd:selector xpath="character"/> <xsd:field xpath="friend-of"/> </xsd:keyref>
These capabilities are nearly independent of the other features in a schema. They are disconnected from the definition of the datatypes. The only point anchoring them to the schema is the place where they are defined, which establishes the scope of the uniqueness constraints.