Using XSLT 1.0, how do I check whether the value in the variable exists or not?
I am assigning the value to the variable initially from my XML data and then need to check whether it exits or not:
<xsl:variable name="DOC_TYPE">
<xsl:value-of select="name(./RootTag/*[1])"/>
</xsl:variable>
<xsl:if test="string($DOC_TYPE) = ''">
<xsl:variable name="DOC_TYPE">
<xsl:value-of select="name(./*[1])"/>
</xsl:variable>
</xsl:if>
The above is not working as expected. What I need is if <RootTag>
exists in my data then the variable should contain the child node below the <RootTag>
. If <RootTag>
does not exist then the DOC_TYPE should be the first Tag in my XML data.
Thanks for your response.
Try this
You can't re-assign variables in XSLT. Variables a immutable, you can't change their value. Ever.
This means you must decide within the variable declaration what value it is going to have:
A few other notes:
'./RootTag'
is redundant. Every XPath you don't start with a slash is relative by default, so saying'RootTag'
is enough<xsl:value-of select="name(*[1])"/>
already results in a string (names are strings by definition), so there is no need to do<xsl:if test="string($DOC_TYPE) = ''">
, a simple<xsl:if test="$DOC_TYPE = ''">
sufficestest="..."
expression - any non-empty node-set evaluates totrue
<xsl:if>
) would go out of scope immediately(meaning right at the</xsl:if>
).It only exists if you have assigned it. There's no reason to test it for existence.
See also here