Re: Problem with key!

Hi Cyrill,

> I road many article to the theme unique, key an keyref but i'm still 
> not understanding how it works.
>
> In my projekt there is an element user with the attribute *id*. The 
> user  element can be found many times but the id must always be a 
> different value.
>
> <user id="1">
>     <name></name>
>     <email></email>
> </user>
> <user id="2">
>     <name></name>
>     <email></email>
> </user>
>
> I thougt it would be possible with "key", wouldn't it? If not, how 
> would you realize this problem? 

Yes, this is certainly one of the usecases for the xs:key mechanism in 
W3C XML Schema. In your example I guess you're schema look something 
like this:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
elementFormDefault="qualified">
    <xs:element name="SomeRoot">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="user" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="name" type="xs:string"/>
                            <xs:element name="email" type="xs:string"/>
                        </xs:sequence>
                        <xs:attribute name="id" use="required" 
type="xs:string"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Now if you want to make sure that all the user/@id are unique within the 
whole document you add the following xs:key declaration to the element 
declaration for the SomeRoot element:

<xs:key name="uniqueId">
    <xs:selector xpath=".//user"/>  <!-- All descendant "user" elements 
to the "SomeRoot" element must be unique... -->
    <xs:field xpath="@id"/>          <!-- ...in terms of the "id" 
attribute -->
</xs:key>

So, your schema should now look like this:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
elementFormDefault="qualified">
    <xs:element name="SomeRoot">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="user" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="name" type="xs:string"/>
                            <xs:element name="email" type="xs:string"/>
                        </xs:sequence>
                        <xs:attribute name="id" use="required" 
type="xs:string"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
       
        <xs:key name="uniqueId">
            <xs:selector xpath=".//user"/>
            <xs:field xpath="@id"/>
        </xs:key>
    </xs:element>
</xs:schema>

Cheers,
/Eddie

Received on Tuesday, 30 July 2002 19:30:50 UTC