xslt 1.0 将 xs:date 转换为特定的日期格式 DD-MON-YYYY

xslt 1.0 to convert xs:date to a specific dateFormat 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 中的数据岛来映射月份的名称。我将 tns 命名空间定义为 http://towelie.namespace.

样本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-JUN-2017

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

并且数据岛可以由外部 XML 文件替换。例如,每种语言一个。