1

What's exactly the difference between ['#'] and [.='#']? Is there any difference at all?

In e.g. the following expressions:

<xsl:template match="a/@href[.='#']">...</xsl:template>
<xsl:template match="a/@href['#']">...</xsl:template>
wolfrevo
  • 6,651
  • 2
  • 26
  • 38

1 Answers1

3

A predicate filters, if the contained expression is not true. [.='#'] tests if the string content of the current context (.) equals #, thus the first template would return all @href attributes for links like <a href="#">...</a>.

The second template does not contain a boolean statement, and it also isn't numerical (so it would be a positional test). It will be evaluated as given by the boolean function:

Function: boolean boolean(object)

The boolean function converts its argument to a boolean as follows:

  • a number is true if and only if it is neither positive or negative zero nor NaN
  • a node-set is true if and only if it is non-empty
  • a string is true if and only if its length is non-zero
  • an object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type

Here, we have a non-empty string with effective boolean value true, thus the predicate in your second template will never filter anything.


A predicate like in //a[@href] on the other hand would filter for all links containing an @href attribute (here, we filter for a node-set).

Jens Erat
  • 37,523
  • 16
  • 80
  • 96
  • `thus the first query would return all @href attributes for links like` .. This is at least no true for XPath 1.0.. http://3v4l.org/39iRA – hek2mgl Feb 17 '14 at 14:15
  • You omitted the `/@href` in the XPath expression. If you add it to resemble the query from the question, it will exactly do what I described in the answer. – Jens Erat Feb 17 '14 at 14:18
  • @JensErat Thank you for the explanation and the hint to boolean evaluation. I just reread the specs and realized that I had forgotten that "A PredicateExpr is evaluated by evaluating the Expr and converting the result to a boolean". – wolfrevo Feb 17 '14 at 14:27