XSLT 1.0 Substring then select distinct



I am quite new to xslt, so any help will be much appreciated. Below is my sample xml file.



<DocumentElement>
<Records>
<date>2014-07-01 00:00</date>
</Records>

<Records>
<date>2014-08-03 00:00</date>
</Records>
<Records>
<date>2013-08-03 00:00</date>
</Records>
<DocumentElement>


What I need is just to select distinct years from the dates.


Currently I have the below xslt which brings duplicate years.



<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://ift.tt/tCZ8VR"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:ms="urn:schemas-microsoft-com:xslt">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="/">

<xsl:variable name="years" select="DocumentElement/Records/date"/>

<ul>
<xsl:for-each select="$years">
<li>
<xsl:element name="a">

<xsl:attribute name="href">
<xsl:value-of select="concat('?archive=',substring( ., 1, 4))"/>
</xsl:attribute>

<xsl:value-of select="substring( ., 1, 4)"/>
</xsl:element>

</li>
</xsl:for-each>
</ul>
</xsl:template>

</xsl:stylesheet>


Which gives me the results below:



<ul>
<li>
<a href="?archive=2014">2014</a>
</li>
<li>
<a href="?archive=2014">2014</a>
</li>
<li>
<a href="?archive=2014">2013</a>
</li>
</ul>


But my expected result should be



<ul>
<li>
<a href="?archive=2014">2014</a>
</li>

<li>
<a href="?archive=2014">2013</a>
</li>
</ul>


I tried the following below but I get empty output



<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://ift.tt/tCZ8VR"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:ms="urn:schemas-microsoft-com:xslt">
<xsl:output method="xml" indent="yes"/>


<xsl:template match="/">

<xsl:variable name="years" select="substring(DocumentElement/Records/date, 1, 4)"/>

<ul>
<xsl:for-each select="$years[not(.=preceding::*)]">
<li>
<xsl:element name="a">

<xsl:attribute name="href">
<xsl:value-of select="concat('?archive=',substring( ., 1, 4))"/>
</xsl:attribute>

<xsl:value-of select="substring( ., 1, 4)"/>
</xsl:element>

</li>
</xsl:for-each>
</ul>
</xsl:template>

</xsl:stylesheet>


Any help will be much appreciated. thanks.


No comments:

Post a Comment