Xml – How to select first and last elements via XPath

xmlxpathxslt

Here is a sample XML, and I am trying to figure out how to select first node value and exit the loop. If I use following XSLT tag

<xsl:value-of select="fruits/fruit"/> 

it returns "apple mango banana" but expected result should be "apple"

<fruits>
  <fruit>apple</fruit>
  <fruit>mango</fruit>
  <fruit>banana</fruit>
</fruits>

I'd also like to select the last fruit without knowing how many fruit exist a priori. So, for the above example, I'd like to return "banana" without knowing that there are 3 fruit elements.

Best Answer

First

You can select the value of the first fruit (of the root fruits element) via fruit[1]:

<xsl:value-of select="(/fruits/fruit)[1]"/> 

will return "apple" as requested.


Last

You can select the value of the last fruit via fruit[last()]:

<xsl:value-of select="(/fruits/fruit)[last()]"/> 

will return "banana" as requested without knowing how many fruits exist a priori.