XML Schema Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.00

Defining Complex Datatypes - "complexType" Element

This section describes a tutorial example on how to define a complex datatype to be used to declare an element that can accept attributes and/or sub elements.

If element is declared with a simple datatype, for example, the "string" built-in datatype, the element must be "simple" - not allowed to have any attributes and any sub (child) elements.

If you want to declare an element to accept attributes or sub elements, you need to use the Complex Type Definition Component.

Rule 1. The Complext Type Definition Component allows you to define a new complex datatype, which can be used to declare elements to accept attibutes and/or sub (child) elements.

Rule 2. The XML represention of a Complex Type Definition Component is a "complexType" element.

Rule 3. A "complexType" must have "name" attribute, if it is used to define a named datatype.

Rule 4. A simple way to specify an attribute in an "complexType" is to add an "attribute" component.

Rule 5. A simple way to specify a list of sub elements is to add a "sequence" element component.

Here is an example schema document, term.xsd, that declares element "term" to accept two sub (child) elements and one attribute:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- term.xsd
 - Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
-->

 <!-- Using a complex datatype -->
 <xs:element name="term" type="termType"/>

 <!-- Defining "termType" -->
 <xs:complexType name="termType">
  <xs:sequence>
   <xs:element name="name" type="xs:string"/>
   <xs:element name="definition" type="xs:string"/>
  </xs:sequence>
  <xs:attribute name="update" type="xs:date"/>
 </xs:complexType>

</xs:schema>

The following XML document, term.xml, conforms to term.xsd:

<?xml version="1.0"?>
<term update="2007-01-01">
 <name>Extensible</name>
 <definition>Capable of being extended.</definition>
</term>

Sections in This Chapter

Schema and Schema XML Representation

Checking Schema Documents - XsdSchemaChecker.java

Creating Schema Documents - "schema" Element

Declaring Root Elements - "element" Element

Specifying Element Datatype - "type" Attribute

Using XML Schema Built-in Datatypes

Using XML Schema Built-in Datatypes Incorrectly

Validating XML Documents again Schema Documents

Deriving New Simple Datatypes - "simpleType" Element

Defining Complex Datatypes - "complexType" Element

Validation Error Examples on Complex Datatypes

Dr. Herong Yang, updated in 2007
Defining Complex Datatypes - "complexType" Element