What is the precedence among operators in XPath?

2020-07-27 02:49发布

问题:

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?

回答1:

XPath Operator Order Precedence

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

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).