Re: [xsl] Lookup tables

Subject: Re: [xsl] Lookup tables
From: "James A. Robinson" <jim.robinson@xxxxxxxxxxxx>
Date: Thu, 15 Mar 2007 18:43:46 -0700
> ancestor::node()//LookUp/Parameter[@key = 'key_to_lookup'].

In XSLT 2.0 it is simple to do this using the form of fn:key
which allows you to pass in a context node.  In XSLT 1.0 I've
seen people use this trick of changing context through
for-each and document(''):

<xsl:stylesheet version="1.0" xmlns:myns="uri.my.namespace"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>

  <xsl:output method="text" />

  <xsl:key match="myns:data" name="myns:table-lookup" use="@key" />

  <xsl:variable name="myns:lookup-table">
    <myns:data key="a" value="1.0" />
    <myns:data key="b" value="2.0" />
    <myns:data key="c" value="3.0" />
  </xsl:variable>

  <xsl:template match="/">
    <xsl:variable name="input" select="'b'" />
    <xsl:variable name="result">
      <xsl:for-each select="document('')">
        <xsl:value-of
          select="key('myns:table-lookup', $input)/@value"/>
      </xsl:for-each>
    </xsl:variable>
    <xsl:value-of select="concat($input, ' = ', $result)" />
  </xsl:template>

</xsl:stylesheet>

In XSLT 2.0 you don't have to pull any tricks:

<xsl:stylesheet version="2.0" xmlns:myns="uri.my.namespace"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>
  
  <xsl:output method="text"/>
  
  <xsl:key name="myns:table-lookup" match="myns:data" use="@key" />

  <xsl:variable name="myns:lookup-table">
    <myns:data key="a" value="1.0" />
    <myns:data key="b" value="2.0" />
    <myns:data key="c" value="3.0" />
  </xsl:variable>

  <xsl:template match="/">
    <xsl:variable name="input" select="'b'" />
    <xsl:variable name="result"
       select="key('myns:table-lookup', $input, $myns:lookup-table)/@value"/>
    <xsl:value-of select="concat($input, ' = ', $result)" />
  </xsl:template>

</xsl:stylesheet>

Both result in 'b = 2.0'

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
James A. Robinson                       jim.robinson@xxxxxxxxxxxx
Stanford University HighWire Press      http://highwire.stanford.edu/
+1 650 7237294 (Work)                   +1 650 7259335 (Fax)

Current Thread