XSD Complex Elements
Complex elements contain other elements and/or attributes.
What is a complex element?
A complex element is an XML element that contains other elements and/or attributes.
There are four types of complex elements:
- Empty elements
- Elements that contain other elements
- Elements that contain only text
- Elements that contain both elements and text
Note:All of the above elements can contain attributes!
Examples of complex elements
The complex element, "product", is empty:
The complex element, "employee", contains only other elements:
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>
The complex XML element, "food", contains only text:
The complex XML element, "description", contains both elements and text:
It happened on <date lang="norwegian">03.03.99</date> ....
</description>
How to define a complex element?
Look at this complex XML element, "employee", which contains only other elements:
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>
In XML Schema, we have two ways to define a complex element:
1. By naming 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, then only "employee" can use the specified complex type. Note that its child elements, "firstname" and "lastname", are enclosed in the indicator <sequence>. This means that the child elements must appear in the order in which they are declared. You will learn more about indicators in theXSD Indicatorssection.
2. The "employee" element can use the type attribute, which is used to reference the name of the complex 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, then several elements can use the same complex type, like 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 use an existing complex element as a base 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>