owagh
owagh

Reputation: 3528

Selecting the last element in the whole document with XSLT

I want to select the last node matching a particular pattern anywhere in the document.

I was trying something like

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <xsl:copy-of select="//node_name[last()]"/>
  </xsl:template>
</xsl:stylesheet>

However, when running this with Saxon 9.4 on the following document :-

<a>
  <node_name attr="1"/>
  <b>
    <c>
    </c>
    <node_name attr="2"/>
  </b>
</a>

I get this output where the copy statement lies :-

<node_name attr="1"/><node_name attr="2"/>

Whereas i actually want the output :-

<node_name attr="2"/>

What am I missing out on here?

Also, the nature of my document is such that I do not know in advance what the exact path to this node will be (since it's composed of a bunch of recursive elements).

Upvotes: 0

Views: 162

Answers (1)

choroba
choroba

Reputation: 241918

You are not looking for a node_name that is last, you are looking for the last of all the node_names. Therefore, the following XPath expression should work:

(//node_name)[last()]

Upvotes: 2

Related Questions