问题
My question is regarding the order of execution in XPath.
I have an expression such as:
//person[@created and customFunction(.)]
My problem is that my custom function is quite compute heavy and I only wish for it to run on nodes that have the created attribute set. Will @created
always be evaluated before customFunction
? I could cook up a program to test this, but in reality the success of such an experiment is no guarantee, at least not in the long term.
If this is a matter of XPath implementation i am using .NET 4.0.
回答1:
XPath 1.0 does short-circuit evaluation, in XPath 2.0 and XPath 3.0 it is implementation-dependant.
According to XPath 1.0 specs, section 3.4: booleans:
An or expression [...] The right operand is not evaluated if the left operand evaluates to true.
An and expression [...] The right operand is not evaluated if the left operand evaluates to false.
According to XPath 2.0 specs, section 3.6: Logical Expressions and XPath 3.0 specs, section 3.8: Logical Expressions:
If XPath 1.0 compatibility mode is true [...] it is defined that when there is no need to evaluate the second operand in order 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 a logical expression are evaluated is implementation-dependent. In this case, an or-expression can return true if the first expression evaluated is true, and it can raise an error if evaluation of the first expression raises an error. Similarly, an and-expression can return false if the first expression evaluated is false, and it can raise an error if evaluation of the first expression raises an error. As a result of these rules, a logical expression is not deterministic in the presence of errors, as illustrated in the examples below.
When using XPath 2.0 or XPath 3.0 you can find out whether the current implementation does short-circuit evaluation by evaluating the following example expression:
true() or name(1234)
The function name
returns the name of the node parameter, or it raises an error if you pass it for example a number, so:
- If it returns true without rising an error then the implementation does short-circuit evaluation.
- If an error is raised the implementation doesn't do short-circuit evaluation (as it has evaluated the right operand which was not neccessary).
回答2:
You can also rewrite it as
//person[@created][customFunction(.)]
This way it only be evaluated for subset filter out by first predicate
来源:https://stackoverflow.com/questions/18386129/does-xpath-do-short-circuit-evaluation-of-logical-expressions