Search code examples
xmlxsltxslt-2.0

Add current date as value to a tag in ISO 8601 format XSLT


I have an xml like below:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<properties>
<entry key="user">1234</entry>
</properties>

I want to add two new tags one contain the value of current date in ISO 8601 format and another one with the date set to current date + 10 years in ISO 8601 format and transform it into a new xml file using xslt, the output xml should be like this

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<properties>
<entry key="user">1234</entry>
<entry key="doc:uploadDate">2017-07-04T22:18:08Z</entry>
<entry key="doc:deleteDate">2027-07-04T22:18:08Z</entry>
</properties>

I am using the below xslt.

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

    <xsl:variable name="currentDate">
        <xsl:value-of select="current-dateTime()" />
    </xsl:variable>

    <xsl:template match="entry[@key='doc:uploadDate']">
        <xsl:copy>
            <xsl:apply-templates select="@*" />
            <xsl:value-of
                select="replace(normalize-space($currentDate),
        '^(\d{2})-(\d{2})-(\d{4})\s+(.*)','$3-$1-$2T$4Z')" />
        </xsl:copy>
    </xsl:template>

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

Could someone please help me with this..


Solution

  • You can add a duration of ten years to the current date:

        <xsl:variable name="curr-date" select="current-dateTime()"/>
        <entry>
            <xsl:value-of select="$curr-date"/>
        </entry>
        <entry>
            <xsl:value-of select="$curr-date + xs:yearMonthDuration('P10Y')"/>
        </entry>