Validation

The <xsl:element>, <xsl:attribute>, <xsl:copy>, <xsl:copy-of>, <xsl:document> and <xsl:result-document> instructions (see Constructing Nodes and Basic Flow Control) can all carry type and validation attributes. This makes it possible to perform XSD validation on the generated XML during an XSLT transformation, using <xsl:import-schema> to bring a schema into scope.

<?xml version="1.0" encoding="UTF-8"?>
<!-- transactions_transformed.xsd -->
<xs:schema
   xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <xs:complexType name="rootType">
      <xs:sequence>
         <xs:element name="elem"/>
         <xs:element name="elem"/>
         <xs:element name="elem"/>
         <xs:element name="elem"/>
         <xs:element name="elem"/>
      </xs:sequence>
   </xs:complexType>
   <xs:element name="elem">
      <xs:complexType>
         <xs:simpleContent>
            <xs:extension base="xs:int">
               <xs:attribute name="id"
                                 type="xs:NMTOKEN" use="required"/>
            </xs:extension>
         </xs:simpleContent>
      </xs:complexType>
   </xs:element>
</xs:schema>

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
         xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
         xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <xsl:output method="xml" indent="yes"/>
   <xsl:import-schema
               schema-location="transactions_transformed.xsd"/>
   <xsl:template match="/">
      <xsl:element name="root" type="rootType">
         <xsl:element name="elem" type="xs:byte">
            <xsl:value-of select="50"/>
         </xsl:element>
         <xsl:element name="elem" validation="strip">
            <xsl:value-of select=" 'Hello' "/>
         </xsl:element>
         <xsl:element name="elem" validation="preserve">
            <xsl:value-of select=" 'Hello' "/>
         </xsl:element>
         <xsl:element name="elem" validation="strict">
            <xsl:attribute name="id">E1</xsl:attribute>
            <xsl:value-of select="100"/>
         </xsl:element>
         <xsl:element name="elem" validation="lax">
            <xsl:attribute name="id">E2</xsl:attribute>
            <xsl:value-of select="200"/>
         </xsl:element>
      </xsl:element>
   </xsl:template>
</xsl:stylesheet>

50 Hello Hello 100 200
The type and validation attributes must not appear together on the same instruction. type validates against a built-in type such as xs:integer, or against a type defined in the imported schema. validation performs a global validation against the declared schema, and accepts one of: <xsl:import-schema> may omit the schema-location attribute, in which case the XSD is given as child content of the element instead.

The book's examples predate XSD 1.1; the current XSD Recommendation (Part 1: Structures and Part 2: Datatypes) is 1.1, which adds features such as assertions and conditional type assignment on top of the 1.0-era constructs shown here.