XML Schema - Key constraint on two two elements

296 views Asked by At

My .xml file is something like this:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file.xsd">
  <parent id="">
    <child>
      <part>A1</part>
    </child>
  </parent>
  <another-parent name="AAA">
    <part name="A1"/>
    <part name="A2"/>
    <part name="A3"/>
  </another-parent>
  <another-parent name="BBB">
    <part name="A1"/>
  </another-parent>
</root>

What I want is:

  1. name of <another-parent> must be unique. And it is ok.
  2. name of <part> must be unique within name of <another-parent> is placed. And it is ok.
  3. <part name="A1"> inside <child> must be a keyref of <another-parent>. And I can't do that.

For the first point, I used the following and it works properly.

<xsd:key name="anotherParentKey">
    <xsd:selector xpath="another-parent"/>
    <xsd:field xpath="@name"/>
</xsd:key>

For the second one I used this one in the element declaration:

<xsd:key name="partKey">
    <xsd:selector xpath="part"/>
    <xsd:field xpath="./@name"/>
</xsd:key>

It works now.

But for the third part, I tried to put this code in the (the first common ancestor) but it doesnt work:

<xsd:keyref name="roadSegmentRef" refer="roadSegmentKey">
    <xsd:selector xpath="identifiedEntity/place/roadSegment" />
    <xsd:field xpath="." />
</xsd:keyref>

But what I get is only:

cvc-identity-constraint.4.3: Key 'partRef' with value 'A1' not found for identity constraint of element 'parent'.   file.xml    /sheet/xsd  line 19 XML Problem
1

There are 1 answers

2
Michael Kay On

You haven't shown us WHERE you put these declarations, and my guess is that you put them in the wrong place.

If you want every X within some Y to have a unique value for Z, then your key/unique declarations need to go in the element declaration for Y; the selector needs to select X starting from Y, and the fields need to select Z starting from X.