Formatting DateTime in xslt 1.0

2019-09-04 22:38发布

I am trying to Format my DateTime 2005-08-01T12:00:00 in XSL 1.0. I tried using substring functions but 'T' is still coming. I want my output to come like this -

<YEAR>2005</YEAR>
<MONTH>08</MONTH>
<DAY>01</DAY>
<HOUR>12<HOUR/>
<MINUTE>00<MINUTE/>
<SECOND>00<SECOND/>

How to write snippet of this and remove 'T' from the incoming value?

1条回答
可以哭但决不认输i
2楼-- · 2019-09-04 23:31

You can use the substring function for this. Remember, that that the indexing of each character in the string starts at 1 not 0. So, to get the year you would do this (assuming you are currently positioned on a date element)

<YEAR><xsl:value-of select="substring(., 1, 4) " /></YEAR>

Here is the full XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="xml" indent="yes" />

   <xsl:template match="date">
      <date>
         <YEAR><xsl:value-of select="substring(., 1, 4) " /></YEAR>
         <MONTH><xsl:value-of select="substring(., 6, 2) " /></MONTH>
         <DAY><xsl:value-of select="substring(., 9, 2) " /></DAY>
         <HOUR><xsl:value-of select="substring(., 12, 2) " /></HOUR>
         <MINUTE><xsl:value-of select="substring(., 15, 2) " /></MINUTE>
         <SECOND><xsl:value-of select="substring(., 18, 2) " /></SECOND>
      </date>
   </xsl:template>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

When applied to the following XML

<dates>
   <date>2005-08-01T12:00:00</date>
</dates>

THe following is output

<dates>
   <date>
      <YEAR>2005</YEAR>
      <MONTH>08</MONTH>
      <DAY>01</DAY>
      <HOUR>12</HOUR>
      <MINUTE>00</MINUTE>
      <SECOND>00</SECOND>
   </date>
</dates>

Obviously you would have to be sure the dates always came in with the same format for this to work.

查看更多
登录 后发表回答