Complex Types

A schema assigns a type to each element and attribute it declares. In Example 17-5, the fullName element has a complex type. Elements with complex types may contain nested elements and have attributes. Only elements can contain complex types. Attributes always have simple types.

Since the type is declared using an xs:complexType element embedded directly in the element declaration, it is also an anonymous type, rather than a named type.

New types are defined using xs:complexType or xs:simpleType elements. If a new type is declared globally with a top-level element, it needs to be given a name so that it can be referenced from element and attribute declarations within the schema. If a type is defined inline (inside an element or attribute declaration), it does not need to be named. But since it has no name, it cannot be referenced by other element or attribute declarations. When building large and complex schemas, data types will need to be shared among multiple different elements. To facilitate this reuse, it is necessary to create named types.

To show how named types and complex content interact, let’s expand the example schema. A new address element will contain the fullName element, and the person’s name will be divided into a first- and last-name component. A typical instance document would look like Example 17-6.

Example 17-6. addressdoc.xml after adding address, first, and last elements
<?xml version="1.0"?> <addr:address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ...

Get XML in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.