Does XPath perform a short check on logical expressions?

My question is about the execution order in XPath.

I have an expression like:

//person[@created and customFunction(.)] 

My problem is that my user-defined function is quite complex, and I just want it to run on nodes that have a set of attributes created. Will @created be always checked before customFunction ? I could have prepared a program to test this, but in fact the success of such an experiment is not a guarantee, at least not in the long run.

If this is an XPath implementation issue, I am using .NET 4.0.

+4
source share
2 answers

XPath 1.0 does a short circuit assessment; in XPath 2.0 and XPath 3.0 it is implementation dependent .

According to the XPath 1.0 specification, section 3.4: booleans :

An or expression [...] The correct operand is not evaluated if the left operand is evaluated as true .

and the expression [...] The correct operand is not evaluated if the left operand evaluates to false .

According to the XPath 2.0 specification, section 3.6: Logical expressions and XPath 3.0, section 3.8: Logical expressions :

If the XPath 1.0 compatibility mode is true [...] , then it is determined that when there is no need to evaluate the second operand to determine the result, then no error can occur as a result of evaluating the second operand .

If XPath 1.0 compatibility mode is false, the order in which the operands of the logical expression are evaluated is implementation dependent . In this case, the or-expression true can be returned if the first evaluated expression is true, and it can if the evaluation of the first expression causes an error. Similarly, an and-expression can return false if the first expression evaluates to false, and this can cause an error if evaluating the first expression causes an error. As a result of these rules, a logical expression is not deterministic in the presence of errors, as shown in the examples below.

When using XPath 2.0 or XPath 3.0, you can find out if the current implementation is evaluating a short circuit by evaluating the following example expression:

 true() or name(1234) 

The name function returns the name of the node parameter or causes an error if you pass it, for example, a number, therefore:

  • If it returns true without raising the error, the implementation evaluates the short circuit.
  • If an error occurs, the implementation does not evaluate the short circuit (because it evaluated the right operand, which was not necessary).
+3
source

You can also rewrite it as

 //person[@created][customFunction(.)] 

That way, it will only be evaluated for the subset filter using the first predicate

+3
source

Source: https://habr.com/ru/post/1498435/


All Articles