XSLT define a variable and check if it exists after

11,747

Since you're using XSLT 1.0, you could use string() to do the test.

Here's an example stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/*">
        <xsl:variable name="foo" select="bar"/>
        <results>
            <xsl:choose>
                <xsl:when test="string($foo)">
                    <foo>DEFINED</foo>
                </xsl:when>
                <xsl:otherwise>
                    <foo>NOT DEFINED</foo>
                </xsl:otherwise>
            </xsl:choose>           
        </results>
    </xsl:template>

</xsl:stylesheet>

Note that white-space is collapsed so <bar> </bar> will return false. Also, string() will work when testing an element directly instead of a variable.

Here's some input/output examples:


Input

<test>
    <bar/>
</test>

or

<test>
    <bar></bar>
</test>

or

<test>
    <bar>    </bar>
</test>

Output

<foo>NOT DEFINED</foo>

Input

<test>
    <bar>x</bar>
</test>

Output

<foo>DEFINED</foo>

If you could use XSLT 2.0, you could declare the variable as an xs:string and just use the variable name in the test (test="$foo").

Example:

<xsl:stylesheet version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xs">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/*">
        <xsl:variable name="foo" select="bar" as="xs:string"/>
        <results>
            <xsl:choose>
                <xsl:when test="$foo">
                    <foo>DEFINED</foo>
                </xsl:when>
                <xsl:otherwise>
                    <foo>NOT DEFINED</foo>
                </xsl:otherwise>
            </xsl:choose>           
        </results>
    </xsl:template>

</xsl:stylesheet>
Share:
11,747

Related videos on Youtube

bignay2000
Author by

bignay2000

Updated on September 14, 2022

Comments

  • bignay2000
    bignay2000 about 1 year

    I am attempting to transform an XML document. First, I am defining a global variable:

     <xsl:variable name="foo"><xsl:value-of select="bar"/></xsl:variable>
    

    Now there is a chance that the XML I'm transforming has <bar>some data</bar> defined. There is also a chance that it is not defined.

    Once I declare the global variable below, I'm trying to output the following if it is defined:

    <foo>DEFINED</foo>
    

    and if it's not defined:

    <foo>NOT DEFINED</foo>
    

    I am using <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    What's the best way of going about this?