Jens
Jens

Reputation: 9150

XSD allow attribute only depending on other attribute value

Suppose I have an XML element, food, that can take on one of two forms:

<food kind="juice" />
<food kind="fruit" sort="apple" />

In my XSD I would like to specify that the sort attribute can only exist for the <food> element iff the kind="fruit". The attribute sort would not be acceptable for other kind values. It looks like a simple attribute implication might work but I could not find more details on this.

How can I specify such a dependency?

Upvotes: 3

Views: 2520

Answers (1)

kjhughes
kjhughes

Reputation: 111726

You can do this using XSD 1.1's Conditional Type Assignment:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
           elementFormDefault="qualified"
           vc:minVersion="1.1"> 
  <xs:element name="food">
    <xs:alternative test="@kind = 'juice'" type="JuiceType"/> 
    <xs:alternative test="@kind = 'fruit'" type="FruitType"/>
  </xs:element>
  <xs:complexType name="JuiceType">
    <xs:sequence>
      <!-- ... -->
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="FruitType">
    <xs:sequence>
      <!-- ... -->
    </xs:sequence>
    <xs:attribute name="sort"/>
  </xs:complexType>
</xs:schema>

Do consider, however, an alternative design that's expressible in both XSD 1.1 and 1.0 that's generally preferable:

<juice/>
<fruit sort="apple"/>

That is, rather than have a kind attribute, use the element name to convey kind.

Upvotes: 4

Related Questions