Recipe6.4.Using Types for Safety and Precision


Recipe 6.4. Using Types for Safety and Precision

Problem

XSLT 1.0's limited type checking put limitations on how robust your stylesheets could be.

Solution

Use XSLT 2.0's extended type system to create precise and type-safe functions and templates.

Use the as attribute on elements that hold or return data.

These elements include xsl:function, xsl:param, xsl:template, xsl:variable, and xsl:with-param.

Use the type attribute on elements that create data.

These elements include xsl:attribute, xsl:copy, xsl:copy-of, xsl:document, xsl:element, and xsl:result-document.

Discussion

All conforming XSLT 2.0 processors allow you to use the simple data types such as xs:integer or xs:string to describe variables or parameters. Further, these types can be used with the symbols *, + and ? to describe sequences of these simple types:

<xsl:stylesheet version="2.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  xmlns:xs="http://www.w3.org/2001/XMLSchema" > <!-- x is a sequence of zero or more strings --> <xsl:variable name="x" select="para" as="xs:string*"/> <!-- y is a sequence of one or more strings. We code the select in a way      that guarantees this although if you knew there must be at least one      para element, you could ommit the if expression --> <xsl:variable name="y"                select="if (para) then para else ''"                as="xs:string+"/> <!-- z is a sequence of one or more strings.  --> <xsl:variable name="z" select="para[1]" as="xs:string?"/> </xsl:stylesheet>

With a schema-aware processor, you can go even further and refer to both simple and complex types from a user-defined schema. A schema-aware processor must be made aware of user-defined types via the top-level instruction xsl:import-schema:

<xsl:stylesheet version="2.0"       xmlns:xsl="http://www.w3.org/1999/XSL/Transform"       xmlns:xs="http://www.w3.org/2001/XMLSchema"      xmlns:my="http://www.mydomain.com/ns/my"> <xsl:import-schema schema-location="my-schema.xsd"/> <xsl:template match="/">  <!--Validate that the resulting element conforms to my:BookType -->  <xsl:element name="Book" type="my:BookType">      <xsl:apply-templates/>  </xsl:element> </xsl:template> <!-- ... --> </xsl:stylesheet>

You should not use xsl:import-schema if you do not have access to a schema-aware processor. If you use a schema-aware processor but wish to make your stylesheets compatible with non-schema-aware processors, then you should use the attribute use-when="system-property('xsl:schema-aware') = 'yes'" on all elements that require a schema-aware processor.




XSLT Cookbook
XSLT Cookbook: Solutions and Examples for XML and XSLT Developers, 2nd Edition
ISBN: 0596009747
EAN: 2147483647
Year: 2003
Pages: 208
Authors: Sal Mangano

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net