Re: [xsl] generic sort based on attribute names

Subject: Re: [xsl] generic sort based on attribute names
From: "Joris Gillis" <roac@xxxxxxxxxx>
Date: Sun, 23 Jan 2005 10:42:29 +0100
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