Professional XML Schemas

Complex Types

Complex types define the attributes an element can carry, and the child elements that an
element can contain. Whenever we want to allow an element to carry an attribute or contain a child
element, we have to define a complex type.

The Customer element declared in the Customer.xsd example
is allowed to contain three child elements (FirstName, MiddleInitial, and
LastName), and therefore needs to be a complex type. We gave the Customer
element a complex type using the complexType element nested inside the element that
declared Customer. We then declared the number of child elements the element
Customer is allowed to contain inside the complexType element and its
compositor sequence, like so:

This is not allowed because we need to define the complex type in order for the
Customer element to contain child elements.

The complex type defined above is known as an anonymous complex type. This is because
it is nested within the element declaration (Customer, in this case). If we wanted more than one
element to contain the same child elements and carry the same attributes, then we would create
a named complex type, which would apply the same restrictions to the content of our new element. We
look at named complex types in Chapter 3.

Let's quickly add to the Customer element in our example XML document, by giving
it an attribute called customerID, so that we can see how we declare attributes. We want the
new document to look as follows:

We declare an attribute using an element called attribute. As with the element
declaration, it carries an attribute called name whose value is the name of the attribute.
Remember the value of an attribute is always a simple type; in this case we want our customerID
attribute to be represented as an integer, so we can use the built-in type of integer to restrict
the value of the attribute to an integer value.

Note the distinction that elements and attributes are declared, while simple
and complex types are defined.

Let's start to look at each of the schema constructs in greater depth. [Continued in
part 2 - Ed.]