![]() |
![]() | ![]() | ![]() | Altova Mailing List Archives>Archive Index >microsoft.public.xsl Archive Home >Recent entries >Thread Prev - xsl:variables. >Thread Next - Re: xsl:variables. Re: xsl:variables.To: NULL Date: 3/27/2008 2:41:00 PM
Guoqi Zheng wrote:
> I got a XML which I just need to display them based on Alphabet order,
> and at the beginning of every Alphabet, I write out the Alphabet letter.
Assuming the input XML is
<root>
<item>Canada</item>
<item>America</item>
<item>Belgium</item>
<item>Benelux</item>
<item>Australia</item>
<item>China</item>
</root>
then this stylesheet
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="text"/>
<xsl:key name="by-letter" match="item" use="substring(., 1, 1)"/>
<xsl:template match="root">
<xsl:apply-templates select="item[generate-id() =
generate-id(key('by-letter', substring(., 1, 1))[1])]" mode="group">
<xsl:sort select="substring(., 1, 1)" data-type="text"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="item" mode="group">
<xsl:value-of select="concat(substring(., 1, 1), ' ')"/>
<xsl:apply-templates select="key('by-letter', substring(., 1, 1))">
<xsl:sort select="." data-type="text"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="item">
<xsl:value-of select="concat(' ', ., ' ')"/>
<xsl:if test="position() = last()">
<xsl:text> </xsl:text>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
creates the following result:
A
America
Australia
B
Belgium
Benelux
C
Canada
China
With XSLT 2.0 you can achieve the same as follows:
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:output method="text"/>
<xsl:template match="root">
<xsl:for-each-group select="item" group-by="substring(., 1, 1)">
<xsl:sort select="substring(., 1, 1)"/>
<xsl:value-of select="concat(current-grouping-key(), ' ')"/>
<xsl:apply-templates select="current-group()">
<xsl:sort select="." data-type="text"/>
</xsl:apply-templates>
</xsl:for-each-group>
</xsl:template>
<xsl:template match="item">
<xsl:value-of select="concat(' ', ., ' ')"/>
<xsl:if test="position() = last()">
<xsl:text> </xsl:text>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
--
Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
| ![]() | ![]() | ![]() |
| Company | Legal | Press | Partners | Careers | Sitemap | Contact Us | Altova Blog | |||||
|
