Search code examples
xmlxsdxsd-validationxml-validation

XSD unique: why does field/@xpath="." not work?


I have a problem while validating some unique-constrains in XML using XSD. (I am validating with XMLlint) I have the following structure:

<xsd:element name="elem" type="elemType" >
      <xsd:unique name="uniqueJob">
        <xsd:selector xpath=".//jobs/job"/>
        <xsd:field xpath="."/>
    </xsd:unique>
</xsd:element>

Where jobs has a complex type deeply nested in the <elem> (I am using <jobs> more then once, thats why I defined the constraint in the root-elem) :

       <xsd:complexType name="jobType">
            <xsd:sequence>
                <xsd:element name="job" minOccurs="0" maxOccurs="3" />
            </xsd:sequence>
        </xsd:complexType>

My problem now is the following: if I have something like

            <jobs>
                <job>Programmer</job>
                <job>Scientist</job>
            </jobs>

it does somehow don't validate. I Get the following error from XMLlint: Element 'job': The XPath './/jobs/job' of a field of unique identity-constraint 'uniqueJob' does evaluate to a node of non-simple type. but 'job' is a simple type. What I am missing here? Thanks in Advance!

PS: I want to achieve that in each <jobs> tag each job is unique.


Solution

  • Change

        <xsd:selector xpath=".//jobs/job"/>
        <xsd:field xpath="."/>
    

    to

        <xsd:selector xpath=".//jobs"/>
        <xsd:field xpath="job"/>
    

    Explanation

    • The former requires that job elements be unique within the scope of itself – always true anyway.

    • The latter requires that job elements be unique within the scope of their parent jobs elements – likely your actual intention.

    See also