Subject: Re: [xsl] The longest node in a node set From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx> Date: Fri, 19 Jul 2002 10:03:13 +0100 |
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
Current Thread |
---|
|
<- Previous | Index | Next -> |
---|---|---|
[xsl] The longest node in a node se, Antonio Fiol Bonnín | Thread | RE: [xsl] The longest node in a nod, Michael Kay |
[xsl] in XSL other than d-o-, Jochen Metzger | Date | RE: [xsl] in XSL other than , Julian Reschke |
Month |