Sorting XML with XSLT and ColdFusion

On June 28, 2010, in ColdFusion, by Anuj Gakhar

I came across a requirement today, where I had to sort a XML file by one of the attributes in one of its child nodes. I did some searching and came across these excellent posts by Ben Nadel.  Obviously, that gave me some headstart and it was clear that XSLT was the way to go.  I have not used a lot of XSLT in the past so my knowledge is a bit limited in this area.

After reading a couple of articles on the subject and understanding some basic stuff – here is what I came up with.

I will use the same XML file I used before in one of my previous posts. The code is below :-

[xml]
<cffile action="read" file="#expandpath(‘books.xml’)#" variable="myXml" />
<cfxml variable="myXsl">
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes" />
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>

<xsl:template match="*|@*|comment()|processing-instruction()|text()">
<xsl:copy>
<xsl:apply-templates select="*|@*|comment()|processing-instruction()|text()" />
</xsl:copy>
</xsl:template>

<xsl:template match="catalog">
<xsl:copy>
<xsl:apply-templates>
<xsl:sort select="price" data-type="number" />
<xsl:sort select="substring(@id,3,10)" data-type="number" />
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
</cfxml>
<cfoutput>
#XmlTransform(myXml, myXsl)#
</cfoutput>
[/xml]

The above XSLT does a few things. It first specifies the output format to be XML. It then copies everything including comments and attributes as is. And then it applies the Sort. The magic is done by these 2 lines of code :-

[xml]
<xsl:sort select="price" data-type="number" />
<xsl:sort select="substring(@id,3,10)" data-type="number" />
[/xml]

The first one sorts the XML by price. The second line sorts the XML by the book’s id attribute ignoring the first 2 characters.

I know I could have simply used Ben’s UDF to do this but I wanted to get a good understanding of what is going on here in terms of XSLT.

Tagged with:  

One Response to Sorting XML with XSLT and ColdFusion

  1. James says:

    Thanks for the article… extremely useful…
    Regards
    James
    http://www.tilogeo.com

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2011 Anuj Gakhar
%d bloggers like this: