XSD 仅允许属性取决于其他属性值 [英] XSD allow attribute only depending on other attribute value

查看:28
本文介绍了XSD 仅允许属性取决于其他属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在我的 XSD 中,我想指定 sort 属性只能存在于 <food> 元素,如果 kind="fruit".对于其他 kind 值,属性 sort 是不可接受的.看起来 简单属性蕴涵 可能会起作用,但我找不到更多细节.>

如何指定这样的依赖项?

解决方案

您可以使用 XSD 1.1 的 条件类型赋值:

<xs:元素名称=食物"><xs:alternative test="@kind = 'juice'" type="JuiceType"/><xs:alternative test="@kind = 'fruit'" type="FruitType"/></xs:element><xs:complexType name="JuiceType"><xs:序列><!-- ... --></xs:sequence></xs:complexType><xs:complexType name="FruitType"><xs:序列><!-- ... --></xs:sequence><xs:attribute name="sort"/></xs:complexType></xs:schema>

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

<fruit sort="apple"/>

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

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?

解决方案

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.

这篇关于XSD 仅允许属性取决于其他属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆