XML 架构,为什么 xs:group 不能是 xs:all 的 child?

XML schema, why xs:group can't be child of xs:all?

根据this page(和我的实践),xs:group 元素不能是xs:all 的child。 所以像

<xs:group name="g">
    <xs:element name="first" type="xs:string"/>
    <xs:element name="last" type="xs:string"/>
</xs:group>
<xs:all>
    <xs:group ref="g" minOccurs="0" maxOccurs="1"/>
    <xs:element name="id" type="xs:string"/>
</xs:all>

无效,因为组不能在 xs:all 内。但是我想定义一个模式,其中两个元素(上例中的firstlast)既存在又不存在,所以我将它们组合在一起。然后我想使组成为 xs:all 的一部分,因为组可以以任何顺序与其他元素(例如上面的 id 元素)一起出现。换句话说,我希望有几个元素作为一个整体是可选的。如果 xs:group 无法成为 xs:all 的 child,我该如何实现?

XML Schema 1.0 only permits xs:element(和 xs:annotation)在 xs:all.

<all
  id = ID
  maxOccurs = 1 : 1
  minOccurs = (0 | 1) : 1
  {any attributes with non-schema namespace . . .}>
  Content: (annotation?, element*)
</all>

不允许xs:groupxs:sequencexs:choice

XML Schema 1.1 permits xs:elementxs:anyxs:group xs:all:

<all
  id = ID
  maxOccurs = (0 | 1) : 1
  minOccurs = (0 | 1) : 1
  {any attributes with non-schema namespace . . .}>
  Content: (annotation?, (element | any | group)*)
</all>

注意:允许无序元素听起来很理想,但很少真正需要。通常 xs:sequence 在实践中就足够了。

如果您愿意放弃无序要求,您可以(即使在 XSD 1.0 中)要求 firstlast 到 "both exist or neither of them exist" 如下:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="a">
    <xs:complexType>
      <xs:sequence>
        <xs:sequence minOccurs="0">
          <xs:element name="first" type="xs:string"/>
          <xs:element name="last" type="xs:string"/>
        </xs:sequence>
        <xs:element name="id" type="xs:string"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>