XML Schema compound elements
XSD Compound elements
Compound elements contain other elements and/or attributes.
h2>What is a composite element?
A compound element refers to an XML element that contains other elements and/or attributes.
There are four types of compound elements:
Empty elements
Elements that contain other elements
Elements containing only text
Elements containing both elements and text
Note: All of the above elements can contain attributes!
Example of compound element
The compound element, "product", is empty:
The compound element, "employee", contains only other elements:
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>
Compound XML element, "food", contains only the text:
Compound XML element, "description" contains elements and text:
It happened on <date lang="norwegian">03.03.99</date> ....
</description>
How to define compound element?
Look at this compound XML element, "employee", containing only other elements:
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>
In XML Schema, we have two ways to define compound elements:
1. By To name this element, you can directly declare the "employee" element, like this:
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
If you use the method described above, only "employee" can use the specified composite type. Notice that its child elements, "firstname" and "lastname", are enclosed in the indicator <sequence>. This means that child elements must appear in the order in which they are declared. You'll learn more about indicators in the XSD Indicators section.
2. The "employee" element can use the type attribute. The function of this attribute is to reference the name of the composite type to be used:
<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
If you use the method described above, several elements can use the same composite type, such as this:
<xs:element name="student" type="personinfo"/>
<xs:element name="member" type="personinfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
You can also base a compound element on top of an existing compound element and then add some elements, like this:
<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="fullpersoninfo">
<xs:complexContent>
<xs:extension base="personinfo">
<xs:sequence>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>