xsl-list
[Top] [All Lists]

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

2008-09-16 00:14:47
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(_at_)CraneSoftwrights(_dot_)com
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



--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--