Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select first and last elements via XPath?

Tags:

xml

xslt

xpath

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.

like image 597
user3767641 Avatar asked Apr 05 '16 01:04

user3767641


People also ask

How do you select the last element in XPath?

Using XPath- last() method, we can write the Java code along with the dynamic XPath location as: findElement(By. xpath("(//input[@type='text'])[last()]"))

How do you select the first element in XPath?

Use the index to get desired node if xpath is complicated or more than one node present with same xpath. You can give the number which node you want.

How do I select the second element in XPath?

//div[@class='content'][2] means: Select all elements called div from anywhere in the document, but only the ones that have a class attribute whose value is equal to "content". Of those selected nodes, only keep those which are the second div[@class = 'content'] element of their parent.


1 Answers

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.

like image 175
kjhughes Avatar answered Sep 17 '22 19:09

kjhughes