Implementing Lookup Tables with <xsl:function>

Using document('') to implement lookup tables is a workable approach, but we can simplify things with an XSLT function. With a function, we can invoke getStateName() to resolve a state abbreviation to a state name; that’s much simpler than invoking document('')/*/states:name[@abbrev=current()] or something similar. Here’s how our function looks:

<xsl:function name="states:getStateName" as="xs:string">
  <xsl:param name="abbr" as="xs:string"/>
  <xsl:variable name="abbreviations" as="xs:string*"
    select="'AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT',
<!-- state abbreviations removed for brevity -->
            'WV', 'WI', 'WY'"/>
  <xsl:variable name="stateNames" as="xs:string*"
    select="'Alabama', 'Alaska', 'American Samoa','Arizona', 
<!-- state names removed for brevity -->
            'West Virginia', 'Wisconsin', 'Wyoming'"/>
  <xsl:variable name="index"
    select="if (count(index-of($abbreviations, $abbr)) gt 0) 
            then subsequence(index-of($abbreviations, $abbr), 1, 1)
            else 0"/>
  <xsl:value-of 
    select="if ($index gt 0)
            then string(subsequence($stateNames, $index, 1))
            else ''"/>
</xsl:function>

Our function takes a single string, a state abbreviation, as a parameter, and it returns a single string. It uses two variables to store our data; $abbreviations is a sequence of all state abbreviations, and $stateNames is a sequence of all state names. The positions of items in the two sequences match each other. If the abbreviation passed to the function matches the fifth item in ...

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.