[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

RE: [xsl] generic sort based on attribute names


Subject: RE: [xsl] generic sort based on attribute names
From: "Chaitanya Desai" <cdesai@xxxxxxxxxxx>
Date: Sun, 23 Jan 2005 02:19:45 -0800

hi Joris,
thanks for the response. But the collective string lengths are not the same.
In fact I just gave an example here. I have no a priori knowledge of what the
XML looks like. All I know is that the 'concatenated name-value pairs for all
attributes sorted' needs to be the key for sorting.
Thanks


-----Original Message-----
From: Joris Gillis [mailto:roac@xxxxxxxxxx]
Sent: Sun 1/23/2005 1:42 AM
To: xsl-list@xxxxxxxxxxxxxxxxxxxxxx
Subject: Re: [xsl] generic sort based on attribute names

Tempore 04:23:21, die 01/23/2005 AD, hinc in
xsl-list@xxxxxxxxxxxxxxxxxxxxxx scripsit Chaitanya Desai
<cdesai@xxxxxxxxxxx>:

> Suppose
> <root>
>  <e b="bb" y="yy"/>
>  <e z="zz" a="aa"/>
> </root>
> is the XML I want to sort.
> The result of the sort should be
> <root>
>   <e a="aa" z="zz" />
>   <e b="bb" y="yy" />
> </root>
> Thus the attributes within an element are sorted and then the key used
> for sorting elements would be:
> 'az' and 'by' respectively (thus 'az' < 'by').
Hi,

Changes are rather tiny, but if all attribute names happen to have the
same collective string length (like in the example:
length('az')=length('by')), you could use something like this:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">

<xsl:output method="xml" indent="yes"/>

<xsl:template match="root">
	<xsl:variable name="sortkey">
		<xsl:apply-templates select="e" mode="sortkey"/>
	</xsl:variable>
	<xsl:copy>
		<xsl:apply-templates select="e" >
			<xsl:sort select="substring($sortkey,position()*2 - 1, 2)"/>
		</xsl:apply-templates>
	</xsl:copy>
</xsl:template>

<xsl:template match="e" mode="sortkey">
	<xsl:apply-templates select="@*" mode="sortkey">
		<xsl:sort select="." data-type="string"/>
	</xsl:apply-templates>
</xsl:template>

<xsl:template match="@*" mode="sortkey">
	<xsl:value-of select="local-name()"/>
</xsl:template>

<xsl:template match="e">
	<xsl:copy>
		<xsl:apply-templates select="@*" >
			<xsl:sort select="." data-type="string"/>
		</xsl:apply-templates>
	</xsl:copy>
</xsl:template>

<xsl:template match="@*">
	<xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>


regards,
--
Joris Gillis (http://www.ticalc.org/cgi-bin/acct-view.cgi?userid=38041)
Deserta faciunt et innovationem appelant


Current Thread
Keywords
xml