Is there a way to make elements unique in same sequence (choice, all) but not on the whole document.
For example this should work (Both John and Jane have Francis as middlename):
<students xsi:noNamespaceSchemaLocation="stack.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<student>
<name>John</name>
<middlename>Francis</middlename>
<middlename>Mike</middlename>
<lastname>Doe</lastname>
</student>
<student>
<name>Jane</name>
<middlename>Francis</middlename>
<lastname>Doe</lastname>
</student>
</students>
But this should not work (John has two similar middle names):
<students xsi:noNamespaceSchemaLocation="stack.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<student>
<name>John</name>
<middlename>Francis</middlename>
<middlename>Francis</middlename>
<lastname>Doe</lastname>
</student>
</students>
I have tried so far following on my .xsd file:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="students">
<xs:complexType>
<xs:sequence maxOccurs="unbounded">
<xs:element name="student">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:sequence minOccurs="0" maxOccurs="5">
<xs:element name="middlename" type="xs:string"/>
</xs:sequence>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:unique name="middlename_unique">
<xs:selector xpath="student/middlename"/>
<xs:field xpath="."></xs:field>
</xs:unique>
</xs:element>
</xs:schema>
But this only makes middlename in general unique not for a single student...
https://www.w3.org/TR/xmlschema-0/#specifyingUniqueness says
XML Schema enables us to indicate that any attribute or element value must be unique within a certain scope. To indicate that one particular attribute or element value is unique, we use the unique element first to "select" a set of elements, and then to identify the attribute or element "field" relative to each selected element that has to be unique within the scope of the set of selected elements.
So I think you want
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="students">
<xs:complexType>
<xs:sequence maxOccurs="unbounded">
<xs:element name="student">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:sequence minOccurs="0" maxOccurs="5">
<xs:element name="middlename" type="xs:string"/>
</xs:sequence>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:unique name="middlename_unique">
<xs:selector xpath="middlename"/>
<xs:field xpath="."/>
</xs:unique>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>