How to select first and last elements via XPath?

不想你离开。 提交于 2020-12-08 05:49:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/36415455/how-to-select-first-and-last-elements-via-xpath

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!