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.
Using XPath- last() method, we can write the Java code along with the dynamic XPath location as: findElement(By. xpath("(//input[@type='text'])[last()]"))
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.
//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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With