3

In this XPath expression: //div[@id=”myID”]|p, does the // operator get applied to both sides of the union operator? Or would this expression simply return all div elements in the document that have an id attribute value of myID and all p elements that are children of the context node?

Is there a reference for XPath operator binding and associativity?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
Clint
  • 900
  • 11
  • 25

1 Answers1

6

XPath Operator Order Precedence

The XPath EBNF grammar implies the following precedence among operators (lowest to highest):

enter image description here

Source: XML Path Language (XPath) 2.0 (Second Edition)

(See also: XML Path Language (XPath) 3.0)


Since // and [] are of higher precedence than | (union), your XPath expression

//div[@id=”myID”]|p

says

  • select all div elements in the document with @id attribute value equal to myID,
  • and select all p elements that are children of the context element,
  • and take the union of those two sets of elements

to produce the final result (as you anticipated in your second interpretation).

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • 4
    Just to add to this, in XPath 1.0 there is no such table, but the precedence is defined implicitly by the grammar. For example the productions `[21] AdditiveExpr ::= MultiplicativeExpr ( ("+" | "-") MultiplicativeExpr )*` and `[22] MultiplicativeExpr ::= UnionExpr ( ("*" | "div" | "idiv" | "mod") UnionExpr )*` tell us that the operands of "+" can contain a "*" or "div" operator, but not vice versa. – Michael Kay Apr 25 '16 at 08:32
  • Should `@` be considered a highest-precedence operator? What about `::`? – MichaelChirico Jun 03 '22 at 05:37
  • Your question reduces to that of `::` because `@` is merely a shortcut for `attribute::`. The table is only a summary of the normative precedence defined in the [EBNF grammar](https://www.w3.org/TR/2010/REC-xpath20-20101214/#id-grammar), where you can find that `::` is part of `ForwardAxis` or `ReverseAxis`, which work their way up to `UnaryExpr`, which you see in the above table summarized as `unary`. As such, consider `::` less as an [XPath operator](https://www.w3.org/TR/xquery-operators/) and more as a defining syntactic part of an axis step, which plays with operators as a `UnaryExpr`. – kjhughes Jun 03 '22 at 11:20