Search code examples
xmlxsltxsdxml-parsing

unique constraint on id not working and it always return true


Hey all I am trying to use unique constraint and here is my xml

<graph>
  <id>g0</id>
  <id>g0</id>
  <name>test</name>
</graph>

now I need to validate it and the validation should return false because id is not unique in order to validate I wrote the following constraint but I get true with no error

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="graph" type="AType"/>
<xsd:complexType name="AType">
    <xsd:sequence>
        <xsd:choice>
            <xsd:sequence>
                <xsd:element name="id" type="xsd:string">
                    <xsd:unique name="nodeId">
                        <xsd:selector xpath="id"/>
                        <xsd:field xpath="."/>
                    </xsd:unique>
                </xsd:element>
                <xsd:element name="id" type="xsd:string">
                    <xsd:unique name="nodeId1">
                        <xsd:selector xpath="id"/>
                        <xsd:field xpath="."/>
                    </xsd:unique>
                </xsd:element>
                <xsd:element name="name" type="xsd:string" />
            </xsd:sequence>
        </xsd:choice>
    </xsd:sequence>
</xsd:complexType>
</xsd:schema> 

Am I missing anything? why my schema does validate the uniqueness of id?


Solution

  • You have put the constraint in the wrong place. Each of the id elements is valid in itself; it's the graph element that is invalid, so that's where the constraint needs to go.

    If the rule is "every X within a Y must have a unique value for Z", then:

    • The unique constraint belongs on Y
    • The selector should select X starting from Y
    • The field should select Z starting from X