0

使用format-date($date, 'yyyy-MM-dd')将日期输出为dd/MM/yyyy

细节

我正在与使用以下日期格式的系统集成:

<SomeDateElement>
    <DAY>21</DAY>
    <MONTH>06</MONTH>
    <YEAR>2017</YEAR>
</SomeDateElement>

要将这些值转换为有效的xs:date/xs:datetime元素,我在 XSLT 中创建了以下逻辑:

匹配任何“假日期”的模板:

<xsl:template match="//*[./YEAR and ./MONTH and ./DAY]">
    <xsl:call-template name="ConvertFakeDateToXmlDateTime">
        <!-- <xsl:with-param name="format">yyyy-MM-DDTHH:mm:ss</xsl:with-param> -->
    </xsl:call-template>
</xsl:template>

格式化任何“假日期”的模板(与上述分开,以便于我希望指定不同格式/通过其他匹配捕获的那些日期轻松重用)。

<xsl:template name="ConvertFakeDateToXmlDateTime">
    <xsl:param name="format" select="yyyy-MM-dd" />
    <xsl:variable name="date" select="concat(./YEAR/text(),'-',./MONTH/text(),'-',./DAY/text())" /> <!-- as="xs:datetime" -->

    <!-- debugging code-->
    <xsl:element name="{concat('DEBUG_',name(.))}">
        <xsl:attribute name="IAmADate">
            <xsl:value-of select="$date"/> <!-- show our date variable's content -->
        </xsl:attribute>
        <xsl:apply-templates select="@* | node()" /> <!-- show the original value -->
    </xsl:element>
    <!-- end debugging code -->

    <xsl:element name="{name(.)}" namespace="{namespace-uri(.)}">
        <xsl:value-of select="msxsl:format-date($date, $format)"/>
    </xsl:element>
</xsl:template>

使用上面的代码和示例输入,我得到以下输出:

<DEBUG_SomeDateElement xmlns="" IAmADate="2017-06-21">
    <DAY>21</DAY>
    <MONTH>06</MONTH>
    <YEAR>2017</YEAR>
</DEBUG_SomeDateElement>
<SomeDateElement xmlns="">21/06/2017</SomeDateElement>

补充笔记

我正在使用 Microsoft .Net 的System.Xml.Xsl.XslCompiledTransform.

我的样式表包括函数的属性/命名空间:xmlns:msxsl="urn:schemas-microsoft-com:xslt"format-date

简单示例

我还尝试通过这样做来简化问题:

<xsl:element name="demo">
    <xsl:value-of select="msxsl:format-date('2017-06-21', 'yyyy-MM-dd')"/>
</xsl:element>

<xsl:element name="demo">
    <xsl:variable name="demoDate" select="2017-06-21" />
    <xsl:value-of select="msxsl:format-date($demoDate, 'yyyy-MM-dd')"/>
</xsl:element>
  • The first example (where date & format are literals) gave <demo>2017-06-21</demo>. ✔</li>
  • The second (where date is a variable) gave <demo>1900-01-01</demo>. ✘</li>

As such, I've been unable to reproduce the exact issue I'm seeing above; though I have now discovered a second issue, implying I've misunderstood something about XSLT variables.

4

1 回答 1

1

You need to quote the values in your selects to make them strings:

<xsl:variable name="demoDate" select="'2017-06-21'" />

and

<xsl:param name="format" select="'yyyy-MM-dd'" />
于 2017-06-22T15:00:51.997 回答