温馨提示:本文翻译自stackoverflow.com,查看原文请点击:xsd - DIfference between group and complexType in XML Schema?
xml xsd

xsd - XML模式中group和complexType之间的区别?

发布于 2020-04-29 13:07:14

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

不带组元素的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具有相同的效果?

查看更多

提问者
Yannis Markou
被浏览
28
mamift 2020-02-11 07:37

您的“ 带有组元素XSD ”示例中的内容不正确:

<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>您可以有一个包含元素的组,这些元素可以具有自己的属性。这实际上是组和复杂类型之间的差异之一。

组只能包含内容的模型或注释,(也就是他们的直接孩子只能是3的一个:<xs:all /><xs:choice /><xs:sequence />,或文档元素)。请参阅第3.7.2节中的https://www.w3.org/TR/xmlschema11-1/#cModel_Group_Definitions

<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>您甚至可以拥有仅定义属性而无法定义的复杂类型,而组不能做到这一点。