Vicky
Vicky

Reputation: 53

net.sf.saxon.trans.XPathException: Arithmetic operator is not defined for arguments of types (xs:string, xs:string)

I am trying to add two variables in xslt2. The Idea is to have next month (and potentially increment the year if its the last month).

I am using the Code is below:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/02/xpath-functions" xmlns:xdt="http://www.w3.org/2005/02/xpath-datatypes" exclude-result-prefixes="xsl xs fn xdt">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <xsl:param name="filter_date"/>

    <xsl:variable name="Current_Date">
        <xsl:choose>
            <xsl:when test="$filter_date">
                <xsl:value-of select="$filter_date"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="format-date(current-date(), '[Y0001][M01][D01]')"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>

    <xsl:variable name="Current_Month" select="substring($Current_Date,5,2)"/>
    <xsl:variable name="Current_Year" select="substring($Current_Date,1,4)"/>
    <xsl:variable name="One">1</xsl:variable>

    <xsl:variable name="Month">
        <xsl:choose>
            <xsl:when test="$Current_Month = '12'">
                <xsl:text>01</xsl:text>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$Current_Month + '0' + $One"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>

    <xsl:variable name="Year">
        <xsl:choose>
            <xsl:when test="$Current_Month = '12'">
                <xsl:value-of select="sum($Current_Year + $One)"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$Current_Year"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>

    <out>
        <xsl:value-of select="concat($Year, $Month, '20')" />
    </out>

</xsl:template>

But I get an error

net.sf.saxon.trans.XPathException: Arithmetic operator is not defined for arguments of types (xs:string, xs:string).

Upvotes: 1

Views: 1898

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167401

If you want to do date arithmetic in XSLT/XPath 2.0 you can simply add a duration to a date, for instance to add a month to the current date use

<xsl:value-of select="current-date() + xs:yearMonthDuration('P1M')"/>

Adding strings with + is not supported in XSLT/XPath, I am not even sure whether you expect that to do string concatenation or to convert the operands to numbers first.

Upvotes: 1

Related Questions