Sometimes we need to sort an XML document by different fields in various order. For instance, here is the XML document:
<?xml version="1.0" encoding="UTF-8"?>
<publications>
<publication>
<author>A. Male</author>
<year>1999</year>
</publication>
<publication>
<author>F. Feng</author>
<author>X. Cao</author>
<year>2011</year>
</publication>
<publication>
<author>J. Allinson</author>
<year>2012</year>
</publication>
<publication>
<author>F. Feng</author>
<author>J. Allinson</author>
<year>1999</year>
</publication>
<publication>
<author>S Lee</author>
<year>2007</year>
</publication>
<publication>
<author>F. Feng</author>
<author>N. Thomas</author>
<year>1999</year>
</publication>
</publications>
We want to sort by year in descending order first, then by first author in ascending order, then by second author (if exists) in ascending order as well. Here is the XSLT (tested in saxon v9):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/publications">
<publications>
<xsl:call-template name="publication"/>
</publications>
</xsl:template>
<xsl:template name="publication">
<publication>
<xsl:for-each select="publication">
<!-- First, sort by pub year -->
<xsl:sort select="year" order="descending"/>
<!-- Second, sort by first author -->
<xsl:sort select="author[1]" order="ascending"/>
<!-- Third, sort by second author (if exists) -->
<xsl:sort select="author[2]" order="ascending"/>
<xsl:copy-of select="."/>
</xsl:for-each>
</publication>
</xsl:template>
</xsl:stylesheet>
No comments:
Post a Comment