pati
pati

Reputation: 135

Why does "foo != 1" behave differently than "not(foo = 1)" in xslt if there's no foo node present?

I had a condition in XSLT like this:

 <xsl:if test="foo != 1">
     <p>This should be shown if foo doesn't equal one</p>
 </xsl:if>

foo is a flag here. If foo was 1 or 0 it worked fine. But if there was no foo element defined the condition returned false as if foo was equal to 1.

I've changed it to

 <xsl:if test="not(foo = 1)">
     <p>This should be shown if foo doesn't equal one</p>
 </xsl:if>

And it began to work as I expected: if there's no foo, the condition will be also true.

Can somebody explain why is it so in XSLT. And what is the best way to check that the node doesn't exist as well as that it doesn't have a specific value?

Upvotes: 1

Views: 81

Answers (2)

Joel M. Lamsen
Joel M. Lamsen

Reputation: 7173

Using the following input

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <test>
        <foo>1</foo>
    </test>
    <test>
        <foo>0</foo>
    </test>
    <test>
        <a>xxx</a>
    </test>    
</root>

and the following stylesheet

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="//test">
        <xsl:choose>
            <xsl:when test="not(foo[.!=1])">
                <p>aaa</p>
            </xsl:when>
            <xsl:otherwise>
                <p>bbb</p>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

the output is

<?xml version="1.0" encoding="utf-8"?>

<p>aaa</p>

<p>bbb</p>

<p>aaa</p>

Upvotes: 0

Tobias Klevenz
Tobias Klevenz

Reputation: 1645

Your first statement says:

if there is a foo element that is not 1

for this to be true a foo element has to exist, otherwise this is false even if there is no foo element at all

your second statement says:

if there is no foo element that is 1 

this is the correct way to do what you want, because it is also true if there is no foo element at all

Upvotes: 1

Related Questions