XPath operator "!=". How does it work?

Keith picture Keith · Jan 7, 2011 · Viewed 45.3k times · Source

XML document:

<doc>
    <A>   
        <Node>Hello!</Node>   
    </A> 

    <B>     
        <Node/>
    </B>  

    <C>
    </C>

    <D/>
</doc>

How would you evaluate the following XPath queries?

/doc/A/Node != 'abcd'  
/doc/B/Node != 'abcd'  
/doc/C/Node != 'abcd'  
/doc/D/Node != 'abcd'  

I would expect ALL of these to evaluate to true.

However, here are the results:

/doc/A/Node != 'abcd'     true
/doc/B/Node != 'abcd'     true
/doc/C/Node != 'abcd'     false
/doc/D/Node != 'abcd'     false

Is this expected behavior? Or is it a bug with my XPath provider (jaxen)?

Answer

Dimitre Novatchev picture Dimitre Novatchev · Jan 7, 2011

Recommendation: Never use the != operator to compare inequality where one or both arguments are node-sets.

By definition the expression:

$node-set != $value

evaluates to true() exactly when there is at least one node in $node-set such that its string value is not equal to the string value of $value.

Using this definition:

$empty-nodeset != $value 

is always false(), because there isn't even a single node in $empty-nodeset for which the inequality holds.

Solution:

Use:

not($node-set = $value)

Then you get all results true(), as wanted.