Name
last()
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 whether a given node is the last in the node-set to which it belongs.
Syntax
[1.0] numberlast()[2.0] xs:integerlast()
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
[1.0] XPath section 4.1, “Node Set Functions.”
[2.0] XQuery 1.0 and XPath 2.0 Functions and Operators section 16, “Context 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"?>
<!-- albums.xml -->
<list xml:lang="en">
<title>Albums I've bought recently:</title>
<listitem>The Sacred Art of Dub</listitem>
<listitem>Only the Poor Man Feel It</listitem>
<listitem>Excitable Boy</listitem>
<listitem xml:lang="sw">Aki Special</listitem>
<listitem xml:lang="en-gb">Combat Rock</listitem>
<listitem xml:lang="zu">Talking Timbuktu</listitem>
<listitem xml:lang="jz">The Birth of the Cool</listitem>
</list>Here is the stylesheet that handles the last <listitem> in the list
differently:
<?xml version="1.0"?>
<!-- last.xsl --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:text>
A test of the last() function:
</xsl:text> <xsl:for-each select="list/listitem"> ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access