Monday, February 7, 2011

xslt: 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>
  • 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:aplly-templates>
    </xsl:template>
    <xsl:template match="node">
        <xsl:value-of select="."/>
    </xsl:template>
    
  • 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>
    
    aku : Just curious, how is that differ from caillou's solution?
    samjudson : It's not - he posted his while I was typing mine. Why he answered his own question is another question...
    aku : Yep, it's happening all the time with me too. After I submit my answer, I'm facing with tons of similar answers :)
    Pierre Spring : i answered to my own question, because, after finding the answer to my problem, i thought that i could use stackoverflow as a repository for the thing i just learned ... makes any sense? i think answering to my own question makes sense in that regard... no?
    Jason Z : I agree with caillou. Jeff has stated on the podcasts that this is an acceptable use of the site.
    From samjudson

0 comments:

Post a Comment