Conditional Type Assignment in XML Schema 1.1

XML Schema (XSD) 1.1 introduces Conditional Type Assignment (CTA), a feature that allows the validation type of an element to be determined dynamically at runtime based on its attribute values. By using the <xs:alternative> element alongside XPath 2.0 test expressions, XSD 1.1 eliminates the limitations of XSD 1.0, where an element’s type was statically bound to its name unless explicitly overridden in the XML instance using the xsi:type attribute.

The Mechanism: <xs:alternative>

In XSD 1.1, conditional type assignment is configured directly within an element declaration using one or more <xs:alternative> elements. Each <xs:alternative> specifies a conditional XPath expression via the test attribute and the corresponding target schema type via the type attribute.

When a validating parser encounters the element, it evaluates the XPath expressions sequentially. The element is validated against the type of the first test attribute that evaluates to true.

Syntax and Implementation

Below is an example demonstrating an <entry> element whose type changes based on the value of its @kind attribute:

<xs:element name="entry" type="xs:anyType">
    <!-- Alternative 1: If @kind is 'book' -->
    <xs:alternative test="@kind = 'book'" type="BookType"/>
    
    <!-- Alternative 2: If @kind is 'journal' -->
    <xs:alternative test="@kind = 'journal'" type="JournalType"/>
    
    <!-- Default Alternative: If no conditions match -->
    <xs:alternative type="GenericEntryType"/>
</xs:element>

Corresponding XML Instances

  1. Validates as BookType:
<entry kind="book">
    <isbn>978-0134685991</isbn>
    <author>Joshua Bloch</author>
</entry>
  1. Validates as JournalType:
<entry kind="journal">
    <issn>0010-4620</issn>
    <volume>64</volume>
</entry>
  1. Validates as GenericEntryType (fallback):
<entry kind="misc">
    <description>General note</description>
</entry>

Key Rules and Processing Constraints

Advantages Over XSD 1.0

In XSD 1.0, conditional data models required consumers to add schema-specific attributes (xsi:type) directly into the business XML documents. XML Schema 1.1 CTA enables domain-specific attributes (such as type, mode, or category) to drive the type validation natively, maintaining separation between domain data and validation logic.