Pierre Spring
Pierre Spring

Reputation: 10675

apply-templates in reverse order

Say I have this given XML file:

<root>
    <node>x</node>
    <node>y</node>
    <node>a</node>
</root>

And I want the following to be displayed:

ayx

Using something similar to:

<xsl:template match="/">
    <xsl:apply-templates select="root/node"/>
</xsl:template>
<xsl:template match="node">
    <xsl:value-of select="."/>
</xsl:template>

Upvotes: 16

Views: 8239

Answers (3)

Pierre Spring
Pierre Spring

Reputation: 10675

You can do this, using xsl:sort. It is important to set the data-type="number" because else, the position will be sorted as a string, end therefor, the 10th node would ge considered before the 2nd one.

<xsl:template match="/">
    <xsl:apply-templates select="root/node">
        <xsl:sort 
            select="position()" 
            order="descending" 
            data-type="number"/>
    </xsl:apply-templates>
</xsl:template>
<xsl:template match="node">
    <xsl:value-of select="."/>
</xsl:template>

Upvotes: 3

imran
imran

Reputation: 461

<xsl:template match="/">
        <xsl:apply-templates select="root/node[3]"/>
        <xsl:apply-templates select="root/node[2]"/>
        <xsl:apply-templates select="root/node[1]"/>
    </xsl:template>
    <xsl:template match="node">
        <xsl:value-of select="."/>
    </xsl:template>

Upvotes: 0

samjudson
samjudson

Reputation: 56853

Easy!

<xsl:template match="/">
    <xsl:apply-templates select="root/node">
        <xsl:sort select="position()" data-type="number" order="descending"/>
    </xsl:apply-templates>
</xsl:template>

<xsl:template match="node">
    <xsl:value-of select="."/>
</xsl:template>

Upvotes: 32

Related Questions