26

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?

Theresa Forster
  • 1,914
  • 3
  • 19
  • 35

3 Answers3

39

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>
khachik
  • 28,112
  • 9
  • 59
  • 94
  • exactly what i was looking for, thanks specially as it's to right to left an fo:flow for arabic documents using 0.23 of FOP (customised and unable to be updated) – Theresa Forster May 04 '11 at 11:33
  • Correct answer. Although for this case there is no need for `descendant-or-self::*/record`. It could be just `record`. –  May 04 '11 at 16:11
5

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)

Nathan
  • 6,095
  • 2
  • 35
  • 61
3

xsl:sort is your friend ;

<xsl:for-each select="descendant-or-self::*/record">
   <xsl:sort select="@id" order="descending" />
   <xsl:value-of select="@id"/>
</xsl:for-each>
AlexanderJohannesen
  • 2,028
  • 2
  • 13
  • 26