Search code examples
xmlxsd

Validate XML with XSD issue


I have this simple XML:

<company>
<departments>
    <department IDDepartment="A01" director="00001234S">
        <employee PassportNumber="00001234S">
            <name>Daniel</name>
            <lastname>Robinson Harris</lastname>
            <salary>2100.86</salary>
        </employee>
        <employee PassportNumber="79300210A">
            <name>Lara</name>
            <lastname>Williams</lastname>
            <salary>1100</salary>
        </employee>
    </department>
    <department IDDepartment="A02" director="09448822T">
        <employee PassportNumber="12345678A">
            <name>Daniel</name>
            <lastname>Brown</lastname>
            <salary>1200</salary>
        </employee>
        <employee PassportNumber="09448822T">
            <name>Tom</name>
            <lastname>Johnson Smith</lastname>
            <salary>2500.50</salary>
        </employee>
    </department>
</departments>

I want to validate with XSD that the "director" value corresponds to the passport number of one of the employees. I'm new to XSD and I'm trying to figure out how to do it. Thanks.


Solution

  • If you don't have XSD 1.1 you can probably do this with key/keyref.

    On the department element, define a key with selector=".", field="@director", and a corresponding keyref with selector="employee", field="@PassportNumber".

    UPDATE

    With the additional information that it can be an employee in a different department, the key needs to be defined as follows:

    On the departments element, define a key with selector="department", field="@director", and a corresponding keyref with selector=".//employee", field="@PassportNumber".