XSLT 1.0 将 XS:DATE 转换为特定日期格式 DD-MON-YYYY



我是xslt的新手,所以这可能是一个基本问题。我正在尝试将以 xs:date 格式收到的日期转换为 DD-MON-YYYY 收到的输入是:<tns:receivedDate>2017-06-27</tns:receivedDate>预期输出<tns:receivedDate>27-JUN-2017</tns:receivedDate>

提前致谢

如果您的意思是将YYYY-MM-DD转换为DD-MMM-YYYY,请尝试:

<xsl:template name="format-date">
<xsl:param name="date"/>
<!-- day -->
<xsl:value-of select="substring($date, 9, 2)"/>
<xsl:text>-</xsl:text>
<!-- month -->
<xsl:variable name="m" select="substring($date, 6, 2)"/>
<xsl:value-of select="substring('JanFebMarAprMayJunJulAugSepOctNovDec', 3*($m - 1)+1, 3)"/>
<xsl:text>-</xsl:text>
<!-- year -->
<xsl:value-of select="substring($date, 1, 4)"/>
</xsl:template>

演示:https://xsltfiddle.liberty-development.net/94rmq7k

在 XSLT-1.0 中,您必须自己实现转换 - 无需内置函数的帮助。

因此,解决方案可能如下所示。它使用 XSLT 中的数据岛来映射月份的名称。我定义了要http://towelie.namespacetns命名空间。

示例 XML:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:tns="http://towelie.namespace">
<tns:receivedDate>2017-06-27</tns:receivedDate>
</root>

解决方案 XSLT-1.0 样式表:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://towelie.namespace" xmlns:month="http://month.val" version="1.0">
<xsl:output method="text" />
<!-- Data island -->
<month:val>
<mon>JAN</mon>
<mon>FEB</mon>
<mon>MAR</mon>
<mon>APR</mon>
<mon>MAI</mon>
<mon>JUN</mon>
<mon>JUL</mon>
<mon>AUG</mon>
<mon>SEP</mon>
<mon>OCT</mon>
<mon>NOV</mon>
<mon>DEC</mon>
</month:val>
<xsl:template match="/root">
<xsl:apply-templates select="tns:receivedDate" />
</xsl:template>
<xsl:template match="tns:receivedDate">
<xsl:variable name="year"  select="substring-before(.,'-')" />
<xsl:variable name="month" select="substring-before(substring-after(.,'-'),'-')" />
<xsl:variable name="day"   select="substring-after(substring-after(.,'-'),'-')" />
<xsl:value-of select="concat($day,'-',document('')/xsl:stylesheet/month:val/mon[number($month)]/text(),'-',$year)" />
</xsl:template>
</xsl:stylesheet>

在此样式表中,输入日期被剖析为三个变量,然后在xsl:value-of中重新组合,将索引应用于数据岛的mon元素。

输出:

27-

六月-2017

最后评论:
这种方法的一个重要优点是您可以根据需要定义月份的名称 - 使用不同语言的不同长度 - 即 JAN、Jan、Janvier、Januar、Enero、...

数据孤岛可以用外部XML文件代替。例如,每种语言一个。

最新更新