16

i wanna make an attribute of an element to be unique like primary key. how to make it?

brainless
  • 5,698
  • 16
  • 59
  • 82

3 Answers3

29

Something like this should work:

<xs:element name="books" maxOccurs="unbounded">
   <xs:complexType>
      <xs:sequence>
         <xs:element name="book" maxOccurs="unbounded">
            <xs:complexType>
               <xs:attribute name="isbn" type="xs:string"/>
            </xs:complexType>
         </xs:element>
      </xs:sequence>
   </xs:complexType>
   <xs:unique name="unique-isbn">
      <xs:selector xpath="book"/>
      <xs:field xpath="@isbn"/>
   </xs:unique>
</xs:element>

Basically, you can define a "uniqueness" constraint using a <xs:unique> element and define what XPath this uniqueness should apply to.

See W3Schools' entry on <xs:unique> for more info.

Niccolò
  • 2,854
  • 4
  • 24
  • 38
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
1

Note: This is not working if you have different namespaces. Then you need the full XPath expression:

This could be like:

<xs:unique name="unique-isbn">
      <xs:selector xpath="theOtherNamespace:book"/>
      <xs:field xpath="@isbn"/>
</xs:unique>
hpu
  • 47
  • 4
1

Note: restriction base must be 'ID'.

<xs:element name="vahicles">
  <xs:complexType>
    <xs:sequence>
       <xs:element ref="vahicle" minOccurs="1" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>



<xs:element name="vahicle">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="shop_name" />
            <xs:element ref="address" />
        </xs:sequence>
        <!-- defining an attribute in vahicle element. -->
    <xs:attribute ref="vshop_id" use="required" />
    </xs:complexType>
</xs:element>

<!-- adding some restriction on the attribute -->
<!-- restriction base must be ID. -->
<xs:attribute name="vshop_id">
    <xs:simpleType>
        <xs:restriction base="xs:ID">
        <xs:pattern value="vsp\d{3}" />
    </xs:restriction>
    </xs:simpleType>
</xs:attribute>



<xs:element name="shop_name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>

Yumick Gharti
  • 1,138
  • 1
  • 7
  • 7