This is the mail archive of the
xsl-list@mulberrytech.com
mailing list .
Re: The longest node in a node set
- From: Jeni Tennison <jeni at jenitennison dot com>
- To: Antonio Fiol Bonnín <fiol at w3ping dot com>
- Cc: xsl-list at lists dot mulberrytech dot com
- Date: Fri, 19 Jul 2002 10:03:13 +0100
- Subject: Re: [xsl] The longest node in a node set
- Organization: Jeni Tennison Consulting Ltd
- References: <3D37033B.5040700@w3ping.com>
- Reply-to: xsl-list at lists dot mulberrytech dot com
Hi Antonio,
> I am trying to find an XPath expression that gives me the longest
> element in a node set.
This is a variation on the "computed maximum" problem. You can't do it
within a single XPath, at least not in XPath 1.0, so you have to use a
different technique. Depending on how many elements you have, you
could use a sort-and-select method:
<xsl:for-each select="//element">
<xsl:sort select="string-length()"
data-type="number"
order="descending" />
<xsl:if test="position() = 1">
Longest: <xsl:value-of select="." />
</xsl:if>
</xsl:for-each>
or you could use a recursive template, by tailoring the one in
Dimitre's FXSL library or by writing your own, such as:
<xsl:template name="findLongest">
<xsl:param name="nodes" select="//element" />
<xsl:param name="max" select="0" />
<xsl:param name="longest" select="/.." />
<xsl:choose>
<xsl:when test="$nodes">
<xsl:variable name="length" select="string-length($nodes[1])" />
<xsl:call-template name="findLongest">
<xsl:with-param name="nodes"
select="$nodes[position() > 1]" />
<xsl:with-param name="max">
<xsl:choose>
<xsl:when test="$max >= $length">
<xsl:value-of select="$max" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$length" />
</xsl:otherwise>
</xsl:choose>
</xsl:with-param>
<xsl:with-param name="longest"
select="$longest[$max >= $length] |
$nodes[1][$length >= $max]" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
Longest: <xsl:value-of select="$longest" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
This template actually finds *all* the elements that are longest, in
case there are several with the same length, whereas using the
sort-and-select method you only get the first with that longest
length.
Cheers,
Jeni
---
Jeni Tennison
http://www.jenitennison.com/
XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list