Search code examples
xmlvalidationxsdunionkeyref

xsd – can I restrict an attribute to a key OR enumeration?


I want to allow example.xml

<defs>
 <def n="a"/>
 <def n="b"/>
</defs>

<refer-to-def n="a"/>
<refer-to-def n="b"/>
<refer-to-def n="predefined"/>
<refer-to-def n="also-predefined"/>

s.t. the only possible values of //refer-to-def/@n are the ones given by //def/@n OR "predefined" OR "also-predefined. In particular, if I added <refer-to-def n="never-defined"/> it should no longer validate.

I can do the first restriction by using

<xs:keyref name="defRef" refer="def">
  <xs:selector xpath=".//refer-to-def" />
  <xs:field xpath="@n" />
</xs:keyref>
<xs:key name="def">
  <xs:selector xpath="./defs/def" />
  <xs:field xpath="@n" />
</xs:key>

but this of course fails if the .xml has <refer-to-def n="predefined"/>.

The second restriction I can do by defining <def>'s n attribute with

  <xs:attribute name="n" use="required">
    <xs:simpleType>
      <xs:union>
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="predefined"/>
            <xs:enumeration value="also-predefined"/>
          </xs:restriction>
        </xs:simpleType>
      </xs:union>
    </xs:simpleType>
    </xs:attribute>

but of course this doesn't include the dynamic list of defs n-values.

How do I combine the two, so n can be either from the dynamic list or from the predefined set, and my example.xml validates?


Solution

  • Can't be done in XSD 1.0.

    In XSD 1.1 you can do anything with assertions.