Search code examples
xmlxpathoperator-precedenceassociativity

What is the precedence among operators in XPath?


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?


Solution

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