XPath function
last()
The size of the current context, which makes [last()] the idiom for selecting the final node in a set.
last() returns the number of nodes in the context the predicate is being evaluated against. Inside a predicate that is the size of the set being filtered, so [last()] selects the final one.
There is no first() — the equivalent is [1], because XPath positions are one-based.
- Syntax
last() → number- Returns
- number
- Kind
- Function
- Version
- XPath 1.0 (libxml2)
Worked examples
Each result below is what the evaluator returned, asserted on every test run. An empty result means an empty node-set — which is an answer, not an error.
What catches people out
- There is no first(). Use [1] — XPath is one-based, and [0] selects nothing at all.
- last() is relative to the context, so //line[last()] means 'the last line among its own siblings', which selects one node per parent rather than one node overall.
- Outside a predicate, last() is the size of the current node list, which is rarely what people mean.
The sample documents
Every example on this page runs against this document. The sitemap one is namespaced on purpose — almost every real XML document is, and that changes which expressions match.
<?xml version="1.0" encoding="UTF-8"?>
<order id="A-1001" tier="gold">
<customer country="NO">Ada Lovelace</customer>
<lines>
<line sku="WIDGET-1" qty="2"><price>14.50</price></line>
<line sku="WIDGET-2" qty="1"><price>39.00</price></line>
<line sku="GIFT-WRAP" qty="1"><price>0.00</price></line>
</lines>
<note> Deliver after 09:00 </note>
</order>Related
Get started
Bring order to the XML your team can't afford to ignore.
Create a free account and get a private workspace to search, validate, diff, and monitor your XML feeds, sitemaps, schemas, and vendor integrations.