Creating a Unique Constraint with an XSD

You can create a Unique constraint within an XSD using the <xs:unique> element.

Examples:

Suppose you have the schema:

<xs:element name="Directory">
   
<xs:complexType>
       
<xs:sequence>
            <xs:element name="Person" maxOccurs="unbounded">
               
<xs:complexType>
                    <xs:attribute name="Username" type="xs:string" use="required" />
                    <xs:attribute name="Age" type="xs:int" use="required" />
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>


Then you could enforce a rule that forces usernames to be unique. You can do this using the Unique element:

<xs:element name="Directory">
   
<xs:complexType>
       
<xs:sequence>
            <xs:element name="Person" maxOccurs="unbounded">
               
<xs:complexType>
                    <xs:attribute name="Username" type="xs:string" use="required" />
                    <xs:attribute name="Age" type="xs:int" use="required" />
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
   
<xs:unique name="MyUserNameUniqueKey">
       
<xs:selector xpath="Person"
/>
        <xs:field xpath="@Username"
/>
    </xs:unique
>
</xs:element>

The selector and field pair specify the data that must be unique, the XPath expressions are relative to the parent element (Directory).

Common Mistakes:

If the schema declares a targetnamespace then the XPath expressions must be fully qualified:

<xs:schema xmlns:mstns="http://tempuri.org/XMLSchema1.xsd" elementFormDefault="qualified" targetNamespace="http://tempuri.org/XMLSchema1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Directory">
       
<xs:complexType>
           
<xs:sequence>
                <xs:element name="Person" maxOccurs="unbounded">
                   
<xs:complexType>
                        <xs:attribute name="Username" type="xs:string" use="required" />
                        <xs:attribute name="Age" type="xs:int" use="required" />
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
       
<xs:unique name="MyUserNameUniqueKey">
           
<xs:selector xpath="mstns:Person" />
            <xs:field xpath="@Username" />
        </xs:unique>
    </xs:element>
</xs:schema>

 

Feedback

Hi, you might want to rename the article. It's spelled "constraint". very useful article tho, helped me a lot.
Thang Vu (10/2/2018 at 11:01 AM)