Monday, August 24, 2009

How to Sort elements/attributes using XSLT

Sort Elements/Attributes using xsl:Sort



Suppose Following is your XML.

<Room seqNum="1" adultNum="2" childNum="4">
<Child age="5"/>
<Child age="7"/>
<Child age="6"/>
<Child age="2"/>
</Room>

And you want a sorted Output like this

<root>
<MinAge>2</MinAge>
<MaxAge>7</MaxAge>
</root>

Then You can use the xsl:sort function as following

<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output indent="yes"/>
<xsl:template match="Room">
<root>
<xsl:for-each select="Child/@age">
<xsl:sort select="." data-type="number"/>
<xsl:if test="position() = 1">
<MinAge><xsl:value-of select="."/></MinAge>
</xsl:if>
<xsl:if test="position() = last()">
<MaxAge><xsl:value-of select="."/></MaxAge>
</xsl:if>
</xsl:for-each>
</root>
</xsl:template>
</xsl:stylesheet>

No comments:

Post a Comment