last() Function |
Returns the position of the last node in the current context. This function is useful for defining templates for the last occurrence of a given element or for testing if a given node is the last in the node-set to which it belongs.
Inputs
None.
Output
A number equal to the number of nodes in the current context. For example, if the current context contains 12 <li> nodes, last() returns 12.
Defined in
XPath section 4.1, Node Set Functions.
Example
We'll use the last() function to handle the last item in a list in a special way. Here's the XML document we'll use:
    <?xml version="1.0"?>
    <list>
      <title>A few of my favorite albums</title>
      <listitem>A Love Supreme</listitem>
      <listitem>Beat Crazy</listitem>
      <listitem>Here Come the Warm Jets</listitem>
      <listitem>Kind of Blue</listitem>
      <listitem>London Calling</listitem>
      <listitem>Remain in Light</listitem>
      <listitem>The Joshua Tree</listitem>
      <listitem>The Indestructible Beat of Soweto</listitem>
    </list>
Here is the stylesheet that handles the last <listitem> in the list differently:
    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

      <xsl:output method="html"/>

      <xsl:template match="/">
        <html>
          <head>
            <title>
              <xsl:value-of select="/list/title"/>
            </title>
          </head>
          <body>
            <h1>
              <xsl:value-of select="/list/title"/>
            </h1>
            <ul>
              <xsl:for-each select="/list/listitem">
                <xsl:choose>
                  <xsl:when test="position()=last()">
                    <li><b>Last, but not least: </b><xsl:value-of select="."/></li>
                  </xsl:when>
                  <xsl:otherwise>
                    <li><xsl:value-of select="."/></li>
                  </xsl:otherwise>
                </xsl:choose>
              </xsl:for-each>
            </ul>
          </body>
        </html>
      </xsl:template>

    </xsl:stylesheet>
When we transform the XML document with this stylesheet, here are the results:
    <html>
    <head>
    <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>A few of my favorite albums</title>
    </head>
    <body>
    <h1>A few of my favorite albums</h1>
    <ul>
    <li>A Love Supreme</li>
    <li>Beat Crazy</li>
    <li>Here Come the Warm Jets</li>
    <li>Kind of Blue</li>
    <li>London Calling</li>
    <li>Remain in Light</li>
    <li>The Joshua Tree</li>
    <li>
    <b>Last, but not least: </b>The Indestructible Beat of Soweto</li>
    </ul>
    </body>
    </html>
When rendered, the HTML file looks like Figure C-7. Generated HTML document