ZVON > Tutorials > XML Schema and Relax NG Tutorial
Index | >> Example 4 / 6 << | Prev | Next |
Contents > Unique and key > Key and nillable

Key and nillable

  1. XML Schema - key and nillable

Please, send all comments, bug-reports, and contributions to Jiri.Jirat@systinet.com. Thank you very much.

XML Schema keys: key, nillable

1. XML Schema - key and nillable

We will use "key" element to define, that the elements "a" under "root" element must have unique value of "id" element.

Valid document


<root xsi:noNamespaceSchemaLocation="incorrect_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <a>
    <id>x</id>
  </a>
  <a>
    <id>y</id>
  </a>
  <a>
    <id>z</id>
  </a>
</root>

Valid document
This document explains, why the Schema is not OK - because it allows the element to be "nil" (empty) on one side, on the other side it must be a "key". If the "id" element had not been declared as a key, the document would have been valid.


<root xsi:noNamespaceSchemaLocation="incorrect_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <a>
    <id xsi:nil="true"/>
  </a>
  <a>
    <id>y</id>
  </a>
  <a>
    <id>z</id>
  </a>
</root>

Incorrect XML Schema (incorrect_0.xsd)
This Schema is not OK, because the element "id" will be validated against a definition, which has attribute "nillable" to "true". That violates 3.11.4 Identity-constraint Definition Validation Rules, 4.2.3 .


<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" >

  <xsd:element name="root" type="myList">
    <xsd:key name="myId">
      <xsd:selector xpath="./a"/>
      <xsd:field xpath="id"/>
    </xsd:key>
  </xsd:element>

  <xsd:complexType name="myList">
    <xsd:sequence minOccurs="1">
      <xsd:element name="a" minOccurs="1" maxOccurs="unbounded">
        <xsd:complexType>
          <xsd:sequence minOccurs="1">
            <xsd:element name="id" type="xsd:NCName" nillable="true"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>