Element vs complexType

When to use Element

If an instance document (xml document) requires an item named Address, then you MUST have an element defined within your xml schema named Address. Otherwise the xml document will never be valid against the schema.

E.g. For the following XML Document item to be valid:

The XML Schema must define a corresponding element:
<xsd:element name=”Address”>…</xsd:element>

Furthermore, if other elements are allowed to act as substitute items, then the item must be declared as an element.

When to use complexType

Any time the above is not true you should consider using a complexType. Even when the above is true, you may still want to create a complexType to define the structure. This is especially true if the structure may be reused by multiple elements.

E.g. If the Address structure may be used by HomeAddress and WorkAddress, you should define Address as a complexType:
<xsd:complexType name=”AddressType”>…</xsd: complexType >

<xsd:element name=” HomeAddress” type=”AddressType” />
<xsd:element name=” WorkAddress” type=”AddressType” />

Note 1: Whilst the complexType could be named “Address” is it good practice to make types distinct from elements, so here we use the name “AddressType”.

Note 2: You could define AddressType as an element and use the “ref” attribute:
<xsd:element name=”AddressType”>…</xsd: element >
<xsd:element name=” HomeAddress” ref=”AddressType” />

However, it is good practice to use complexType for the reusable building blocks that make up your document rules and use element for the actual tags that will be present within the document.

Note 3: If you intend to use the “nillable” attribute, then you MUST use a complexType in the above example, as the ref and nillable attributes are mutually exclusive.