[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: "Joris Gillis" <roac@xxxxxxxxxx>
Date: Tue, 25 Jan 2005 22:32:51 +0100

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

This is the recursive stylesheet I have, to handle a generic XML.
How does the thing you explained with the 'e' fit here.

This is an example of how it could be used;

<xsl:template match="*">
<xsl:variable name="sortkey">
<xsl:for-each select="*">
<xsl:for-each select="@*">
<xsl:sort select="name(.)"/>
<xsl:value-of select="name()"/>
<xsl:for-each select="@*">
<xsl:sort select="name(.)"/>
<xsl:copy-of select="."/>
<!-- the select for this sort needs to be the concatenated name-value pairs of
all the attributes sorted in alphabetical order -->
<xsl:sort select="xx:node-set($sortkey)//e[position()=count(current()/preceding-sibling::*)]"/>

It will convert an input like this:
	<e b="bb" y="yy">
		<node x="123" a="123"/>
		<node x="999" a="999" b="999"/>
	<e z="zz" a="aa"/>

to this:
	<e a="aa" z="zz"/>
	<e b="bb" y="yy">
		<node a="999" b="999" x="999"/>
		<node a="123" x="123"/>

For each element in the source doument, it creates a table of the attributes of all child elements and uses this table (stored in the 'sortkey' variable) to perform the sort.

e.g. when the 'root' element is matched, the 'sortkey' variable contains:

because these entries follow the document order, you can use them as sortkey for the child elements by matching the position:

(please keep in mind that this is an XSLT1.0 solution. The XSLT2.0 solutions of Michael Kay and Dimitre Novatchev are of course better if your XSLT processor can handle them)

Joris Gillis (http://www.ticalc.org/cgi-bin/acct-view.cgi?userid=38041)

Current Thread