Using W3C XML Schema
by Eric van der Vlist
|
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9
Constraints
Unique
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 xs:unique
element. The following declaration done under the declaration of our book
element indicates that the character name must be unique:
<xs:unique name="charName">
<xs:selector xpath="character"/>
<xs:field xpath="name"/>
</xs:unique>
This location of the xs:unique element in the schema gives the
context node in which the constraint holds. By inserting xs:unique
under our book element, we specify that the character has to be unique within
the context of this 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 xs:field element is evaluated relative to the element identified by the xs:selector, and can be an element or an
attribute node. This is the node whose value will be checked for uniqueness. Combinations of
values can be specified by adding other xs:field elements within xs:unique.
Keys
The second construct, xs:key, is similar to
xs:unique except that the value has to be non null (note that
xs:unique and xs:key can both be referenced). To use
the character name as a key, we can just replace the xs:unique by
xs:key:
<xs:key name="charName"> <xs:selector xpath="character"/> <xs:field xpath="name"/> </xs:key>
Keyref
The third construct, xs:keyref, allows us to define a reference to a xs:key or a xs:unique. To show its usage,
we will 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
this same book, we will write, at the same level as we defined our key
constraint, the following:
<xs:keyref name="charNameRef" refer="charName"> <xs:selector xpath="character"/> <xs:field xpath="friend-of"/> </xs:keyref>
These capabilities are almost 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.