Search code examples
xmlxsltxslt-2.0

How to handle variable not defined problem


I need to set a value to a variable that will hold the nodes count for specific xpath that accept some condition. After, I need to use this value. The problem is that if the condition is never accepted, the variable will not be defined, and I'm getting an error when I'm trying to use it .

<xsl:variable name="Bondscounter">
        <xsl:for-each select="//Bonds_RepoSecuSched_List/Bonds_RepoSecuSched[ISINCode != ''] ">
            <xsl:value-of select="position()" />
        </xsl:for-each>
    </xsl:variable>

How can I bypass this problem ?


Solution

  • In XSLT 2.0 your variable will be set to a document node with a single text node child with a string value of the concatenation of those integers from 1 to the number of items selected by your XPath1 — probably not what you want.

    If you want "the nodes count for specific xpath", just use the count() function directly:

    <xsl:variable name="Bondscounter"
         select="count(//Bonds_RepoSecuSched_List/Bonds_RepoSecuSched[ISINCode!=''])/>
    

    As to the variable not being defined, such an issue is independent of the variable's value. You may have a scoping problem, but we cannot assess that without more context.

    1Thanks to Michael Kay for the correction.