Re: [xsl] Newbie question on XSL transformations: multiple sorts on element attributes

Subject: Re: [xsl] Newbie question on XSL transformations: multiple sorts on element attributes
From: Abel Braaksma <abel.online@xxxxxxxxx>
Date: Wed, 07 Feb 2007 01:10:45 +0100
Rob Newman wrote:

Datalogger elements right now are not sorted. Whichever comes first in input.xml gets output first in output.xml. I have no control of the order in input.xml. Hence the need to sort them.

Thanks for the more verbose input. I often have the same trouble getting my point through, but your last clarifications sure make things easier. Let me summarize, to find out if I got the point now:


1. You want to order all datalogger elements based on the only child element of pfarr, which is a pfstring and has an attribute @name='dlt'. Highest number first.
2a. You do not want to order the param elements, because they are already ordered
2b. You do want to order the param elements.


I wasn't sure between 2a and 2b, so I give you both answers. Resolving (1) first:

<xsl:apply-templates select="pfarr/pfarr/pfarr" >
<xsl:sort select="pfstring[@name = 'dlt']" data-type="number" order="descending"/>
</xsl:apply-templates>


What this does is the following: for each pfarr element, it orders for the child "pfstring" that has an attribute '@name' with the value 'dlt'. You may be tempted to use the element names of the output, but you should always use the nodes from the input (no other possibility). The starting point for the expression always is each element that is selected by the enclosing xsl:apply-templates. Here, "pfarr/pfarr/pfarr" returns a selection of "pfarr" elements. These are ordered based on there pfstring children. The trick I always use to find out whether I have a legal path is, append them together:

"pfarr/pfarr/pfarr"  plus   "pfstring[@name = 'dlt']" yields:
pfarr/pfarr/pfarr/pfstring[@name = 'dlt']

if this resulting path is not correct, i.e. does not select anything, the xsl:sort will not have any effect.


Solving 2a: remove the other sorts.


Solving 2b: leave only the following in place to order param elements ascending and by name (in your example, both input and output were sorted, so I wasn't sure you needed this)

 <xsl:apply-templates select="pfstring">
     <xsl:sort select="@name" />
 </xsl:apply-templates>



Sorry about this - hopefully this cleans the canvas and it is clear to all what I am trying to do. Thanks again.

np. See above.


Current Thread