Jimm
Jimm

Reputation: 8505

xsd key not being validated

Can someone explain why my key is not being enforced?

<xs:element name="Cats">
  <xs:complexType>
    <xs:sequence maxOccurs="Unbounded">
       <xs:element name="cat" type="cattype"/>
     </xs:sequence>
  </xs:complexType>
  <xs:key name="CatsKey">
    <xs:selector xpath="cat" />
    <xs:field xpath="cat_id"/>
  </xs:key>
</xs:element>

<xs:complexType name="cattype">
<xs:sequence>
  <xs:element name="cat_id" type="xs:nonNegativeInteger"/>
</xs:sequence>
</xs:complexType>

Now the xml

  <cats>
    <cat>
      <cat_id>1</cat_id>
    </cat>
    <cat>
      <cat_id>1</cat_id>  <-- this should fail, as cat_id 1 already exists
    </cat>
  </cats>

But the xmlparser is not enforcing the key. To my understanding key value should be mandatory and unique. Do i need a keyref or unique for the parser to enforce the key constraint or am i doing something fundementally wrong?

Upvotes: 0

Views: 67

Answers (2)

David Z.
David Z.

Reputation: 5701

You may want to look at example 17-2 on the following site since it looks to cover what you are trying to do http://www.datypic.com/books/defxmlschema/chapter17.html.

EDIT: The feedback is that the key does need to be unique, so I'm removing that part of my response to avoid confusion.

Upvotes: 0

Michael Kay
Michael Kay

Reputation: 163468

Is your data in a namespace perhaps? If so you've fallen into the famous trap of using unqualified names in an XPath expression to refer to namespaced elements.

Upvotes: 1

Related Questions