Casting Between Datatypes

It is possible to cast an atomic value from one atomic datatype to another. We can’t do that with complex types, but it does work for atomic types. Here’s a short example that illustrates this:

<?xml version="1.0"?>
<!-- typecasting.xsl -->
<xsl:stylesheet version="2.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:age="http://www.oreilly.com/xslt"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  
  <xsl:output method="text"/>

  <xsl:import-schema namespace="http://www.oreilly.com/xslt">
    <xs:schema 
      targetNamespace="http://www.oreilly.com/xslt"
      xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:simpleType name="age-type">
        <xs:restriction base="xs:integer">
          <xs:minInclusive value="0"/>
          <xs:maxInclusive value="130"/>
        </xs:restriction>
      </xs:simpleType>
    </xs:schema>
  </xsl:import-schema>

  <xsl:template match="/">
    <xsl:variable name="age” as="age:age-type"
      select="age:age-type(42)"/>
    <xsl:variable name="age-int" as="xs:integer"
      select="$age cast as xs:integer"/>
    <xsl:variable name="float-age" as="age:age-type"
      select="xs:float(42.0) cast as age:age-type"/>
    <xsl:value-of select="$age, $age-int, $float-age"
      separator=", "/>
  </xsl:template>
</xsl:stylesheet>

The three variables at the bottom of the stylesheet are of datatypes age:age-type, xs:integer, and xs:float. Because all of these are numeric types, we can cast a value from one type to another. We still have to follow the restrictions for each datatype; the statement xs:float(148.3) cast as age:age-type ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.