在XSLT 1.0中使用带有分隔符的concat()

时间:2014-03-08 23:06:47

标签: xml xslt xpath xslt-1.0

我正在尝试将月/日/年元素中的字符串连接到显示MM / DD / YYYY的单个值,但我找不到在xslt 1.0中执行此操作的方法,其中包含'/'在xslt 2.0中字符串连接函数的分隔符。我需要在不创建新模板或使用变量/ if-logic的情况下执行此操作,因为我们尚未在课堂上“学习”。我试图连接的代码部分如下所示:

<publishedDate>
<month>7</month>
<day>9</day>
<year>2007</year>
</publishedDate>

目前我能做的最好的是:

<xsl:value-of select="concat(
format-number(publishedDate/month, '##00', 'date'),
format-number(publishedDate/day, '##00', 'date'),
format-number(publishedDate/year, '####', 'date')
)"/>

哪个输出日期如下:03082014

与此同时,为了完成任务,我不得不使用一个看似这样的可怕,冗长的解决方法:

<xsl:value-of select="format-number(publishedDate/month, '##00', 'date')"/>/
<xsl:value-of select="format-number(publishedDate/day, '##00', 'date')" />/
<xsl:value-of select="format-number(publishedDate/year, '####', 'date')" />

正确输出(即03/08/2014)。你们知道使用1.0函数获得此输出的方法吗?谢谢!

2 个答案:

答案 0 :(得分:5)

你快到了。您只需要在'/'本身添加包含concat()的额外参数(它仍然是XSLT 1.0 - 您可以拥有三个以上的术语):

concat(format-number(...), '/', format-number(...), '/', format-number(...))

答案 1 :(得分:2)

XPath 2.0(包含在XSLT 2.0中)将支持使用string-join($sequence, $seperator)通用解决方案:

string-join((
    format-number(publishedDate/month, '##00', 'date'),
    format-number(publishedDate/day, '##00', 'date'),
    format-number(publishedDate/year, '####', 'date')
  ), '/')

这对于连接任意长度的序列尤其重要,这在XPath 1.0中是不可能的。

由于您只想组合固定数量的字符串(年/月/日),因此使用XPath 1.0 / XSLT 1.0提供的concat(...)完全没问题:

concat(
  format-number(publishedDate/month, '##00', 'date'),
  '/',
  format-number(publishedDate/day, '##00', 'date'),
  '/',
  format-number(publishedDate/year, '####', 'date')
)