Reputation: 47
Is there any way to access the parent node's overall position from a for-each loup via xpath?
My XML:
<book>
<part>
<chapter><author>Mary J.</author></chapter>
<chapter><author>John K.</author></chapter>
<chapter><author>Martin F.</author></chapter>
</part>
<part>
<chapter><author>Lisa G.</author></chapter>
<chapter><author>Harry T.</author></chapter>
</part>
</book>
Here's the output I would like to have
Mary J. - 1
John K. - 2
Martin F. - 3
Lisa G. - 4
Harry T. - 5
I do understand why the following does not work, in the given context, but is there any other way to have this done via xpath?
<xsl:template match="/">
<xsl:for-each select=".//author">
<xsl:value-of select="." />
<xsl:text> - </xsl:text>
<xsl:value-of select="ancestor::chapter/position()" />
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
or is the only solution via xsl:number, like this:
<xsl:template match="/">
<xsl:for-each select=".//author">
<xsl:value-of select="." />
<xsl:text> - </xsl:text>
<xsl:number from="book" level="any" select="parent::chapter" />
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
Upvotes: 1
Views: 252
Reputation: 116959
If you want to use the chapter's position, you could do:
<xsl:template match="/book">
<xsl:for-each select="part/chapter">
<xsl:variable name="chapter-number" select="position()" />
<xsl:for-each select="author">
<xsl:value-of select="."/>
<xsl:text> - </xsl:text>
<xsl:value-of select="$chapter-number"/>
<xsl:text> </xsl:text>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
Upvotes: 1