xslt中函数vs模板的优缺点是什么?
我想发送一个unix-timestamp并获得“今天”,“明天”或“下周”等答案。哪种方法最适合这个?
答案 0 :(得分:2)
在命名模板上选择<xsl:function>
的主要原因是函数的可组合性程度要高得多。
编写产生所需结果的<xsl:function>
非常简单方便:
<xsl:function name="my:when" as="xs:string">
<xsl:param name="pDateTime" as="xs:dateTime"/>
<xsl:sequence select=
"for $vToday in xs:dateTime(current-date()),
$vTomorrow in $vToday
+ xs:dayTimeDuration('P1D'),
$vDayAfterTomorrow in $vTomorrow
+ xs:dayTimeDuration('P1D'),
$vNextWeek in $vToday
+ 7* xs:dayTimeDuration('P1D'),
$vNextFortnight in $vNextWeek
+ 7* xs:dayTimeDuration('P1D')
return
if($pDateTime lt $vToday)
then 'in the Past'
else if($pDateTime lt $vTomorrow)
then 'Today'
else if($pDateTime lt $vDayAfterTomorrow)
then 'Tomorrow'
else if($pDateTime lt $vNextWeek)
then 'This week'
else if($pDateTime lt $vNextFortnight)
then 'Next week'
else 'In the Future'
"/>
</xsl:function>
这是一个完整的转型:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:my="my:my">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:sequence select="my:when(current-dateTime())"/>,
<xsl:sequence select="my:when(current-dateTime()
+xs:dayTimeDuration('P1D'))"/>,
<xsl:sequence select="my:when(current-dateTime()
+xs:dayTimeDuration('P2D'))"/>,
<xsl:sequence select="my:when(current-dateTime()
+xs:dayTimeDuration('P3D'))"/>,
<xsl:sequence select="my:when(current-dateTime()
+xs:dayTimeDuration('P4D'))"/>,
<xsl:sequence select="my:when(current-dateTime()
+xs:dayTimeDuration('P5D'))"/>,
<xsl:sequence select="my:when(current-dateTime()
+xs:dayTimeDuration('P6D'))"/>,
<xsl:sequence select="my:when(current-dateTime()
+xs:dayTimeDuration('P7D'))"/>,
<xsl:sequence select="my:when(current-dateTime()
+xs:dayTimeDuration('P8D'))"/>,
<xsl:sequence select="my:when(current-dateTime()
+xs:dayTimeDuration('P9D'))"/>
</xsl:template>
<xsl:function name="my:when" as="xs:string">
<xsl:param name="pDateTime" as="xs:dateTime"/>
<xsl:sequence select=
"for $vToday in xs:dateTime(current-date()),
$vTomorrow in $vToday
+ xs:dayTimeDuration('P1D'),
$vDayAfterTomorrow in $vTomorrow
+ xs:dayTimeDuration('P1D'),
$vNextWeek in $vToday
+ 7* xs:dayTimeDuration('P1D'),
$vNextFortnight in $vNextWeek
+ 7* xs:dayTimeDuration('P1D')
return
if($pDateTime lt $vToday)
then 'in the Past'
else if($pDateTime lt $vTomorrow)
then 'Today'
else if($pDateTime lt $vDayAfterTomorrow)
then 'Tomorrow'
else if($pDateTime lt $vNextWeek)
then 'This week'
else if($pDateTime lt $vNextFortnight)
then 'Next week'
else 'In the Future'
"/>
</xsl:function>
</xsl:stylesheet>
应用此转换时(对任何文档 - 未使用),生成所需的正确结果:
Today,
Tomorrow,
This week,
This week,
This week,
This week,
This week,
Next week,
Next week,
Next week
答案 1 :(得分:1)
在这种情况下,外部功能最适合。
XSLT最适合模式匹配和转换,而不是计算。