Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an XSL:for-each in reverse order

Tags:

I am looking to reverse in XSL/FO a for-each loop.

for instance the xml

<data>   <record id="1"/>   <record id="2"/>   <record id="3"/>   <record id="4"/>   <record id="5"/>   <record id="6"/> </data> 

with the xsl

<xsl:for-each select="descendant-or-self::*/record">    <xsl:value-of select="@id"/> </xsl:for-each> 

I am looking for the output 654321 and not 123456

how is this possible?

like image 913
Theresa Forster Avatar asked May 04 '11 11:05

Theresa Forster


People also ask

What is the correct syntax of for each in XSLT?

The <xsl:for-each> element selects a set of nodes and processes each of them in the same way. It is often used to iterate through a set of nodes or to change the current node. If one or more <xsl:sort> elements appear as the children of this element, sorting occurs before processing.

What is the use of for each in XSLT?

Introduction of XSLT for each. XSLT for each is defined as the iteration process that allows retrieving data from the specified nodes. Based on the selection criteria defined with these functions, it makes a loop through multiple nodes. This works in adding up with the function <xsl:value-of>.

What is XSL sort?

Bob DuCharme. XSLT's xsl:sort instruction lets you sort a group of similar elements. Attributes for this element let you add details about how you want the sort done -- for example, you can sort using alphabetic or numeric ordering, sort on multiple keys, and reverse the sort order.

Is XSL and XSLT the same?

XSLT is designed to be used as part of XSL. In addition to XSLT, XSL includes an XML vocabulary for specifying formatting. XSL specifies the styling of an XML document by using XSLT to describe how the document is transformed into another XML document that uses the formatting vocabulary.


2 Answers

Use xsl:sort not for ordering by @id but for ordering by position():

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/data">     <xsl:for-each select="descendant-or-self::*/record">         <xsl:sort select="position()" data-type="number" order="descending"/>         <xsl:value-of select="@id"/>     </xsl:for-each> </xsl:template> </xsl:stylesheet> 
like image 57
khachik Avatar answered Oct 08 '22 18:10

khachik


Yes, Alexander is right - forgot the data-type though:

<xsl:for-each select="descendant-or-self::*/record">    <xsl:sort select="@id" order="descending" data-type="number" />    <xsl:value-of select="@id"/> </xsl:for-each> 

(without that, you'll run into sorting problems with numbers over 9)

like image 32
Nathan Avatar answered Oct 08 '22 16:10

Nathan