I have the below XML file. I'm trying to create a unique constraint in the XML file so that the id of a book should be unique within the library. I tried creating one but was able to create a unique constraint within the group.
<library>
<group>
<groupName>Group 1</groupName>
<books>
<book>
<name>Aa</name>
<id>11</id>
</book>
<book>
<name>Bb</name>
<id>12</id>
</book>
</books>
</group>
<group>
<groupName>Group 1</groupName>
<books>
<book>
<name>Cc</name>
<id>11</id>
</book>
<book>
<name>Dd</name>
<id>14</id>
</book>
</books>
</group>
</library>
In the given file, Book Name 'Cc' has the id 11 which is the same as Book Name 'Aa' and hence the validation should fail. Please help me on where did I go wrong Here is my xsd file
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="library">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="group">
<xs:complexType>
<xs:sequence>
<xs:element name="groupName" type="xs:string" />
<xs:element name="books">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="book">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="id" type="xs:unsignedByte" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:unique name="uniqueRegAddr">
<xs:selector xpath="book"/>
<xs:field xpath="id"/>
</xs:unique>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
It's the library
element that's invalid if there are two books with the same ID, so the uniqueness constraint needs to be defined for a library
. You've defined a constraint on the validity of a books
element, which is too narrow.