Re: [xsl] Accessing the Nth Occurrence of an Element

Subject: Re: [xsl] Accessing the Nth Occurrence of an Element
From: "G. Ken Holman" <gkholman@xxxxxxxxxxxxxxxxxxxx>
Date: Mon, 15 Sep 2008 21:13:54 -0700
At 2008-09-15 22:16 -0500, mike leonard wrote:
I've been searching for a solution to what I thought was a simple
problem. Given the input XML:

----------------------------------
<forest>
<monkey name="Joe" />
<tree><monkey name="Sam" /></tree>
<tree><monkey name="George" /></tree>
<tree><monkey name="Frank" /></tree>
<tree><treehouse><monkey name="Phil" /></treehouse></tree>
<tree><monkey name="Hans" /></tree>
</forest>
----------------------------------

I want to get the name of the fifth monkey (Phil). I thought this would do it:

----------------------------------
<xsl:template match="forest">
<xsl:text>The fifth monkey's name is: </xsl:text><xsl:value-of
select="//monkey[5]/@name"/>
</xsl:template>
----------------------------------

But this doesn't seem to work.

Correct, because you've asked for all occurrences where there are five monkey siblings and you want the name attribute of the fifth one of those.


It does work fine if all the monkeys
are children of the root element, but I can't count on that always
being the case. Can anyone help me with my monkey trouble?

You want the name of the fifth of all monkeys, not all "fifth monkey sibling" elements.


<xsl:value-of select="(//monkey)[5]/@name"/>

I hope this helps.

. . . . . . . . . . . Ken

t:\ftemp>type mike.xml
<forest>
<monkey name="Joe" />
<tree><monkey name="Sam" /></tree>
<tree><monkey name="George" /></tree>
<tree><monkey name="Frank" /></tree>
<tree><treehouse><monkey name="Phil" /></treehouse></tree>
<tree><monkey name="Hans" /></tree>
</forest>

t:\ftemp>type mike.xsl
<?xml version="1.0" encoding="US-ASCII"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
                version="1.0">

<xsl:output method="text"/>

<xsl:template match="forest">
<xsl:text>The fifth monkey's name is: </xsl:text><xsl:value-of
select="(//monkey)[5]/@name"/>
</xsl:template>

</xsl:stylesheet>
t:\ftemp>xslt mike.xml mike.xsl con
The fifth monkey's name is: Phil
t:\ftemp>



--
Upcoming XSLT/XSL-FO hands-on courses:      Wellington, NZ 2009-01
Training tools: Comprehensive interactive XSLT/XPath 1.0/2.0 video
G. Ken Holman                 mailto:gkholman@xxxxxxxxxxxxxxxxxxxx
Crane Softwrights Ltd.          http://www.CraneSoftwrights.com/s/
Male Cancer Awareness Nov'07  http://www.CraneSoftwrights.com/s/bc
Legal business disclaimers:  http://www.CraneSoftwrights.com/legal

Current Thread