XML Schema中group和complexType的区别是什么?

5
根据w3schoolsgroup元素是complexType元素的子元素。以下XML Schema文件(XSD)可以互换使用吗?

没有group元素的XSD:

<xs:complexType name="personInfo">
    <xs:sequence>
        <xs:element name="firstName" type="xs:string"/>
        <xs:element name="lastName" type="xs:string"/>
    </xs:sequence>
    <xs:attribute name="personId" type="xs:string"  use="required"/>
</xs:complexType>

<xs:element name="person" type="personInfo"/>

XSD中的组元素:

<xs:group name="personGroup">
  <xs:sequence>
    <xs:element name="firstName" type="xs:string"/>
    <xs:element name="lastName" type="xs:string"/>
  </xs:sequence>
  <xs:attribute name="personId" type="xs:string"  use="required"/>
</xs:group>

<xs:complexType name="personInfo">
  <xs:group ref="personGroup"/>
</xs:complexType>

<xs:element name="person" type="personInfo"/>

如果是的话,它们有什么区别?为什么使用group元素,而complexType具有相同的效果?

1
第二个模式发布了一个命名的组定义。该组可以在同一模式中或包含或导入它的其他模式中通过引用多次重复使用。 - ach
我有差不多相同的问题,这个链接对我有些帮助:https://forums.anandtech.com/threads/xml-xsd-group-versus-complex-type.327613/ - SlowLearner
感谢@ach的回答! - Yannis Markou
谢谢@SlowLearner,这也帮了我! - Yannis Markou
1个回答

2
你在 'XSD中使用group元素' 的例子中有错误:

<xs:group name="personGroup">
  <xs:sequence>
    <xs:element name="firstName" type="xs:string"/>
    <xs:element name="lastName" type="xs:string"/>
  </xs:sequence>
  <!-- Wrong -->
  <xs:attribute name="personId" type="xs:string"  use="required"/>
</xs:group>

您不能在<xs:group>的根元素内定义属性。您可以有一个包含元素的组,这些元素可以拥有自己的属性。这实际上是组和复杂类型之间的区别之一。
组只能包含内容模型或注释(即它们的直接子元素只能是以下三者之一:<xs:all /><xs:choice /><xs:sequence />或文档元素)。请参见https://www.w3.org/TR/xmlschema11-1/#cModel_Group_Definitions第3.7.2节。
<group
  id = ID
  maxOccurs = (nonNegativeInteger | unbounded)  : 1
  minOccurs = nonNegativeInteger : 1
  name = NCName
  ref = QName
  {any attributes with non-schema namespace . . .}>
  Content: (annotation?, (all | choice | sequence)?)
</group>

复杂类型和组非常相似,它们可以具有完全相同的内容模型,但是它们也可以定义 <xs:attributes>。你甚至可以定义仅包含属性的复杂类型,而这是组所不能做的。


在哪些特定的使用情况下,我们应该优先选择组而不是复杂类型? - Abdul Mohsin
简单来说,<groups> 的作用是将经常一起使用的元素分组。<attributeGroup> 也是如此。 - mamift

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接