XSL using node index at any level

I have the following xml:

<content>
 <p>para 1<an>test 1</an></p>
 <p>para 2<an>test 2</an></p>
 <p>para 3<an>test 3</an></p>
</content>

and I have the following expression in xsl:

<xsl:template match="/">
 <xsl:text>Count: </xsl:text>
 <xsl:value-of select="count(/content//an)" />
 <xsl:text> Content: </xsl:text>
 <xsl:value-of select="/content//an[2]" />
</xsl:template>

Why does / content // a [1] return "test 1" and / content // a [2] return ""? The graph says there are 3. I am using libxslt.

Thank!

+3
source share
1 answer

This is a FAQ .

Caution should be exercised when using abbreviations //.

//SomeName[1]

means: select all the SomeNameelements in the document that are the first children of SomeNametheir parent. Often selected nodes have more than one (or even all nodes).

The correct way to select only the $ k-th element SomeNamein a document :

(//SomeName)[$k]

In your case, use :

(///) [2]

. [] ( ), //.

+6

All Articles