Thursday, 10 May 2012

Get lastest year in XSLT

 I just come cross a problem, e.g. to get the latest year of a set of publications, the implementation is shown below:

XML code:
<?xml version="1.0" encoding="UTF-8"?>
<publications>
    <publication>
        <author>Frank</author>
        <year>1999</year>
        <title>test1</title>
    </publication>
    <publication>
        <author>Frank</author>
        <year>2012</year>
        <title>test2</title>
    </publication>
    <publication>
        <author>Frank</author>
        <year>1980</year>
        <title>test3</title>
    </publication>
    <publication>
        <author>Frank</author>
        <year>2007</year>
        <title>test4</title>
    </publication>
</publications>

XSLT code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" encoding="UTF-8"/>
   
    <xsl:template match="/">
        <!-- get latest year -->
        <xsl:for-each select="/publications/publication/year">
            <xsl:variable name="currentYear" select="normalize-space(text())"/>
           
            <xsl:if test="self::node()[count(../..//year[. &gt; $currentYear])=0]">
                <latestYear>
                    <xsl:value-of select="$currentYear"/>
                </latestYear>
            </xsl:if>
        </xsl:for-each>
       
    </xsl:template>
   
</xsl:stylesheet>




No comments:

Post a Comment