Creating a Unique Constrant with an XSD

Support FAQ > Liquid XML Studio
You can create a Unique contsrant 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.
i.e.

<
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>

 

 

 


Add Feedback