Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

xml - XSLT 1.0 Get Current DateTime

I have a node in my XML file containing the following:

<Apple>2011-12-01T16:33:33Z</Apple>

I wish to take this line and replace it with the current date and time using the same format as shown above.

YYYY-MM-DDTHH:MM:SSZ

The node is within a namespace declared as 'x'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Playing with DateTime is not possible with XSLT 1.0 alone .. In a similar situations I took help of scripting .. (C#)

Sample XML:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <Apple>2011-12-01T16:33:33Z</Apple>
</root>

Sample XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:cs="urn:cs">
  <xsl:output method="xml" indent="yes"/>
  <msxsl:script language="C#" implements-prefix="cs">
    <![CDATA[
      public string datenow()
     {
        return(DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"));
     }
     ]]>
    </msxsl:script>
      <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="Apple">
      <xsl:copy>
      <xsl:value-of select="cs:datenow()"/>
      </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Resulting Output:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <Apple>2012-02-22T18:03:12Z</Apple>
</root>

The script may reside in a same file (like I have it in my sample XSLT code) or if the code triggering XSLTransformation is C# then move the same code in the calling place :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...