The expired <item>
elements can be selected by a single XPath expression, provided the current date is provided -- either in a variable, or as a literal string.
The solution below uses XSLT 1.0 as the hosting language for XPath 1.0.
For convenience, the current date is specified as a global <xsl:param>
parameter, named pToday
.
Another convenience is that the values for the current year, month and day are defined in the variables $vthisYear
, $vthisMonth
, and $vthisDay
. If necessary, al these variable references can be substituted in the XPath expression with the right-hand-side of their definitions.
The wanted single XPath expression is wrapped-up in the following XSLT transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"
cdata-section-elements="item"/>
<xsl:param name="pToday" select="'04/23/2009'"/>
<xsl:variable name="vthisDay" select=
"substring($pToday,4,2)"/>
<xsl:variable name="vthisMonth" select=
"substring($pToday,1,2)"/>
<xsl:variable name="vthisYear" select=
"substring($pToday,7)"/>
<xsl:template match="/">
<nonExpired>
<xsl:copy-of select=
"/*/item
[$vthisYear < substring(@expires,7)
or
($vthisYear = substring(@expires,7)
and
$vthisMonth < substring(@expires,1,2)
)
or
($vthisYear = substring(@expires,7)
and
$vthisMonth = substring(@expires,1,2)
and
$vthisDay <= substring(@expires,4,2)
)
]
"/>
</nonExpired>
</xsl:template>
</xsl:stylesheet>
When the above transformation is applied on the provided XML document:
<content dataType="XML">
<item type="Promotion" name="Sample Promotion" expires="04/01/2009"><![CDATA[ <p>Details here.</p> ]]></item>
<item type="Promotion" name="Sample Promotion 2" expires="05/01/2009"><![CDATA[ <p>Details here.</p> ]]></item>
</content>
the wanted result is produced:
<nonExpired>
<item type="Promotion" name="Sample Promotion 2" expires="05/01/2009"><![CDATA[ <p>Details here.</p> ]]></item>
</nonExpired>
Note: The solution by oneporter will also work, provided some small errors in it are corrected. Also, it needs rework because of its unrealistic expectation that the current date will be provided in a different format than the dates in the @expires
attributes.