What is the difference between an xs:group
and an xs:sequence
in XML Schema? When would you use one or the other?
The sequence element specifies that the child elements must appear in a sequence. Each child element can occur from 0 to any number of times.
<xs:element name="order" type="ordertype"/> <xs:complexType name="ordertype"> <xs:group ref="custGroup"/> <xs:attribute name="status" type="xs:string"/> </xs:complexType>
<xs:attribute name="attr1" type="string"/> <xs:attribute name="attr2" type="integer"/> </xs:attributeGroup> <xs:complexType name="person">
If the data order is important to the application processing the XML, you should use elements in a sequence.
xs:sequence
- together with xs:choice
and xs:all
- is used to define the valid sequences of XML element in the target XML. E.g. the schema for this XML:
<mainElement> <firstSubElement/> <subElementA/> <subElementB/> </mainElement>
is something like:
<xs:element name='mainElement'> <xs:complexType> <xs:sequence> <xs:element name="firstSubElement"/> <xs:element name="subElementA"/> <xs:element name="subElementB"/> </xs:sequence> </xs:complexType> </xs:element>
xs:group
is used to define a named group of XML element following certain rules that can then be referenced in different parts of the schema. For example if the XML is:
<root> <mainElementA> <firstSubElement/> <subElementA/> <subElementB/> </mainElementA> <mainElementB> <otherSubElement/> <subElementA/> <subElementB/> </mainElementB> </root>
you can define a group for the common sub-elements:
<xs:group name="subElements"> <xs:sequence> <xs:element name="subElementA"/> <xs:element name="subElementB"/> </xs:sequence> </xs:group>
and then use it:
<xs:element name="mainElementA"> <xs:complexType> <xs:sequence> <xs:element name="firstSubElement"/> <xs:group ref="subElements"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="mainElementB"> <xs:complexType> <xs:sequence> <xs:element name="otherSubElement"/> <xs:group ref="subElements"/> </xs:sequence> </xs:complexType> </xs:element>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With