5

According to w3schools, the group element is a child element of the complexType element. Can the following XML Schema files (XSD) be used interchangeably?

XSD without group element:

<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 with group element:

<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"/>

If yes, what is their difference? Why use the group element when complexType has the same effect?

1 Answers1

2

What you have in your 'XSD with group element' example is incorrect:

<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>

You cannot define an attribute inside the root of a <xs:group>. You can have a group that contains elements, and those elements can have their own attributes. This is actually one of the differences between groups and complex types.

Groups can only contain content models or an annotation, (i.e. their immediate children can only be one of the 3: <xs:all />, <xs:choice />, <xs:sequence />, or a documentation element). See https://www.w3.org/TR/xmlschema11-1/#cModel_Group_Definitions under section 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>

Complex types, behave very similarly, as they can also have the exact same content models that groups have, but they also can define <xs:attributes>. You can even have complex types that define nothing but attributes, something you cannot do with groups.

mamift
  • 651
  • 7
  • 18