Re: [xsl] How do you select all unique first-position characters?

Subject: Re: [xsl] How do you select all unique first-position characters?
From: Greg Faron <gfaron@xxxxxxxxxxxxxxxxxx>
Date: Wed, 20 Nov 2002 14:50:51 -0700
At 01:36 PM 11/20/2002, you wrote:
<report-data>
        <person name="Anthony" />
        <person name="Amy" />
        <person name="Amy" />
        <person name="Jim" />
        <person name="Jason" />
</report-data>

I would expect to get A,J from the above XML

Here's most of it for you. I'm having trouble with the initial variable selection though. I'm hoping somebody can take it from here, as I'm stumped now too. I was hoping to do something similar to the usual comparison
not(.=preceding-sibling::node())
but when you throw another command on top of the "preceding-sibling::node()", as in "substring(*, 1, 1)", it uses only the last element found. Anyway, here's the partial stylesheet. Good luck!


<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>
<xsl:output method="xml"/>
<xsl:template match="/">
<!-- Not all the way there yet -->
<xsl:variable name="unique-names" select="report-data/person/@name[
substring(., 1, 1) != substring(parent::person/preceding-sibling::person/@name, 1, 1)
]"/>
<xsl:call-template name="take-firsts">
<xsl:with-param name="nodes" select="$unique-names"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="take-firsts">
<xsl:param name="nodes" select="/.."/>
<xsl:if test="$nodes">
<xsl:value-of select="substring($nodes[position() = 1], 1, 1)"/>
<xsl:if test="$nodes[position() > 1]">
<xsl:text>,</xsl:text>
<xsl:call-template name="take-firsts">
<xsl:with-param name="nodes" select="$nodes[position() > 1]"/>
</xsl:call-template>
</xsl:if>
</xsl:if>
</xsl:template>
</xsl:stylesheet>


Parting thought: If you sort the list before matching, you could change the variable selection to be
substring(., 1, 1) != substring(parent::person/preceding-sibling::person[1]/@name, 1, 1)
(notice the index value of [1] after person on the preceding-sibling axis). This will compare the first character of the current name to the first character of the immediately preceding person's name. If the persons are sorted alphabetically by the name attribute, this will do what you want.



Greg Faron Integre Technical Publishing Co.



XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list


Current Thread