XSD允许属性仅取决于其他属性值

时间:2015-04-07 17:38:01

标签: xml xsd

假设我有一个XML元素food,它可以采用以下两种形式之一:

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

在我的XSD中,我想指定sort属性只能存在<food>元素,如果是kind="fruit"。其他sort值不接受属性kind。看起来simple attribute implication可能有用,但我找不到更多详细信息。

如何指定这样的依赖?

1 个答案:

答案 0 :(得分:2)

您可以使用XSD 1.1&#39; 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>

但是,请考虑一种在XSD 1.1和1.0中可以表达的替代设计,通常更可取:

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

也就是说,不是使用kind属性,而是使用元素名称来传达种类。

相关问题