Anonymous vs Named Types in XML Schema

In XML Schema Definition (XSD), data types govern the structure, constraints, and validation rules for XML elements and attributes, classified broadly into named types and anonymous types. This article breaks down the fundamental definitions of both types, highlights their syntax and implementation differences, and outlines best practices for choosing the right type when architecting an XML Schema.


What is a Named Type?

A named type is a globally defined data type created as a direct child of the root <xs:schema> element. It is assigned an explicit name via the name attribute, making it reusable across multiple element or attribute declarations within the schema (or even across different schemas via import/include).

Characteristics of Named Types:

Syntax Example:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <!-- Definition of a Named Complex Type -->
  <xs:complexType name="AddressType">
    <xs:sequence>
      <xs:element name="Street" type="xs:string"/>
      <xs:element name="City" type="xs:string"/>
      <xs:element name="PostalCode" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>

  <!-- Reusing the Named Type in Multiple Elements -->
  <xs:element name="BillingAddress" type="AddressType"/>
  <xs:element name="ShippingAddress" type="AddressType"/>

</xs:schema>

What is an Anonymous Type?

An anonymous type (also called an unnamed or inline type) is defined directly inside an <xs:element> or <xs:attribute> declaration. It does not have a name attribute and cannot be referenced or reused elsewhere in the schema.

Characteristics of Anonymous Types:

Syntax Example:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <!-- Element with an Anonymous Complex Type -->
  <xs:element name="Product">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Name" type="xs:string"/>
        <xs:element name="Price" type="xs:decimal"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

Key Differences Between Named and Anonymous Types

Feature Named Type Anonymous Type
Declaration Location Root level (child of <xs:schema>) Inline (child of <xs:element> or <xs:attribute>)
Name Attribute Required (name="...") Forbidden / Omitted
Reusability High; can be referenced multiple times None; tied strictly to the parent element
Inheritance & Derivation Supports extension and restriction Cannot be extended or restricted elsewhere
Code Structure Modular and centralized Compact for unique, one-off structures

When to Use Each Type

Choose a Named Type When:

Choose an Anonymous Type When: