andrewjwelch.com
schema-aware.com
schema-aware XSLT and XQuery examples
SAXONICA

Embedding the schema within the stylesheet

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0">
    
    
    
<xsl:import-schema>
        
<xs:schema>            
            
<xs:element name="shapes" type="shapes" />
            
<xs:element name="shape" type="xs:string" />
            
<xs:element name="square" substitutionGroup="shape" />
            
<xs:element name="circle" substitutionGroup="shape" />
            
<xs:element name="triangle" substitutionGroup="shape" />
            
            
<xs:complexType name="shapes">
                
<xs:sequence>
                    
<xs:element ref="square" />
                    
<xs:element ref="circle" />
                    
<xs:element ref="triangle" />
                
</xs:sequence>
            
</xs:complexType>
        
</xs:schema>
    
</xsl:import-schema>
    
    
<xsl:variable name="input">
        
        
<shapes xsl:type="shapes">
            
<square>I'm a square</square>
            
<circle>I'm a circle</circle>
            
<triangle>I'm a triangle</triangle>
        
</shapes>
    
</xsl:variable>
    
    
<xsl:template match="/" name="main">
         
        
<xsl:value-of select="$input//schema-element(shape)" separator="," />        
    
</xsl:template>   
    
</xsl:stylesheet>
The xsl:import-schema element can have either a schema-location attribute, or a child xs:schema element. You can code the schema directly within the xsl:import-schema element which is really useful for types specific to the transform, such as temporary trees.