Using xslt get node value at X position

jasin_89 picture jasin_89 · Sep 17, 2011 · Viewed 32k times · Source

How can I get using xslt, node value at X position, without using foreach

<items>
<item1>x</item1>
<item2>x</item2>
<item3>x</item3>
</items>

This is explained in programming sense:

<xsl:value-of select="Items/Item[2]"/>

==================================================

Just to little expand question, in the following xml:

<items>
    <about>xyz</about>
    <item1>
       <title>t1</title>
       <body>b1</body>
    </item1>
    <item2>
       <title>t2</title>
       <body>b2</body>
    </item2>
    <item3>
       <title>3</title>
       <body>3</body>
   </item3>
</items>

How can I select second's item title.

Answer

Emiliano Poggi picture Emiliano Poggi · Sep 17, 2011

Answer to expanded question. You can use the positional value if you select a node-set of the wanted elements:

<xsl:value-of select="(items//title)[2]"/>

or:

<xsl:value-of select="(items/*/title)[2]"/>

Note the usage of the parenthesis required to return wanted node-set before selecting by position.


You can use what you called "in programming sense". However you need * due to the unknown name of the children elements:

<xsl:value-of select="items/*[2]"/>

Note that nodes-sets in XSLT are not zero-based. In the way above you are selecting the second item, not the third one.

You really need position() when you want compare the current position with a number as in:

<xsl:value-of select="items/*[position()>2]"/>

to select all item with position grater than 2. Other case where position() is indespensible is when position value is a variable of type string:

<xsl:variable name="pos" select="'2'"/>
<xsl:value-of select="items/*[position()=$pos]"/>