11

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.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
user3767641
  • 313
  • 2
  • 4
  • 14

1 Answers1

18

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.

Important: For an explanation of the difference between (/fruits/fruit)[1] and /fruits/fruit[1], see How to select first element via XPath?


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.

See also the explanation regarding the use of () given for the first() case.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • is it correct to say "loop" here? I don't think `xsl:value-of` works as a loop. Have read it somewhere. Just asking for clarification. – Lingamurthy CS Apr 05 '16 at 01:50
  • Right, OP asked specifically about a loop, but in XSLT and XPath it's better to think in declarative concepts such as matching than in procedural concepts such as looping. – kjhughes Apr 05 '16 at 02:10
  • Yes, it may not be called as loop.I just started learning XSLT so probably using wrong terminology...BTW thanks for correcting – user3767641 Apr 11 '16 at 23:20
  • Another Question, how do i find out the value of last node if i don't know how many nodes exist?? – user3767641 Apr 11 '16 at 23:27
  • @user3767641: You can use `last()`. Answer updated to show how. – kjhughes Apr 11 '16 at 23:50