xml 理解 xsd:choice 和 minOccurs

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5214555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 14:35:43  来源:igfitidea点击:

Understanding xsd:choice and minOccurs

xmlxsd

提问by makes

I am having trouble understanding the behavior of the following XML schema:

我无法理解以下 XML 模式的行为:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="rootnode">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:choice minOccurs="1" maxOccurs="2">
          <xsd:element name="e1" minOccurs="1" maxOccurs="2"/>
          <xsd:element name="e2" minOccurs="0" maxOccurs="1"/>
        </xsd:choice>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

I expected at least one instance of either element <e1>or <e2>be required as a child of <rootnode>. Despite my expectations, an empty <rootnode>will validate against this schema:

我期望至少有一个元素的实例<e1>或被<e2>要求作为<rootnode>. 尽管有我的期望,空<rootnode>将根据此模式进行验证:

 > xmllint --schema test.xsd empty.xml
 <?xml version="1.0" encoding="UTF-8"?>
 <rootnode>
 </rootnode>
 empty.xml validates

If I change the minOccursattribute of element e2to something other than "0", I get the behavior I originally expected.

如果我将minOccurselement的属性更改为e2以外的其他内容"0",则会得到我最初预期的行为。

  • It seems as though the mere absenceof element <e2>counts as an occurrence of the xsd:choicein my example.

  • If this is the case, then how come this infinite number of occurrences does not violate the maxOccurslimit in my xsd:choice?

  • 在我的示例中,似乎仅缺少元素就被<e2>视为出现了xsd:choice

  • 如果是这种情况,那么这种无限次出现怎么不违反maxOccursmy 中的限制xsd:choice

回答by Michael Kay

I tell you you can go to the shops at least once and at most twice, and each time you have a choice of what to buy: you can buy apples (either one apple or two apples), or you can buy oranges (either no oranges or one orange).

我告诉你,你可以去商店至少一次,最多两次,每次你都可以选择买什么:你可以买苹果(一个苹果或两个苹果),或者你可以买橙子(要么不买,要么不买)。橙子或一个橙子)。

It's entirely possible that you will choose to go to the shops twice and on each occasion to buy no oranges. So you come back with nothing.

你完全有可能选择去商店两次,每次都不买橙子。所以你什么都没有回来。

回答by David W

Here are the allowable combinations

以下是允许的组合

Two choices:
e1 (1 - 2) + e1 (1 - 2) = e1 x (2 - 4), or
e1 (1 - 2) + e2 (0 - 1), or 
e2 (0 - 1) + e1 (1 - 2), or
e2 (0 - 1) + e2 (0 - 1) = e2 (0 - 2)

One choice (but no new outcomes):
e1 (1-2), or
e2 (0-1)


e1e1, e1e1e1, e1e1e1e1
e1, e1e2, e1e1e2 
e2e1, e2e1e1 
empty, e2, e2e2 

Note that choice[min=2 max=2] would have produced the same set of valid combinations.

请注意, choice[min=2 max=2] 会产生相同的一组有效组合。