[Solved] Syntax Error: XPath Is Not a Legal Expression


That’s a lousy diagnostic message.

Your particular XPath syntax problem

Rather than ||, which is logical OR in some languages, you’re probably looking for |, which is nodeset union in XPath. (That is, assuming you’re not aiming for XPath 3.0’s string concatenation operator.)

How to find and fix XPath syntax problems in general

  1. Use a better tool. Diagnostic messages are hard to write well. While it is not possible in the general case to always specify exactly what to fix to repair a syntax error, the best tools help the most. If your tool says no more than XPath syntax error, you can definitely learn more by attempting to evaluate your XPath using a better tool:

    • oXygen XML Editor using Saxon:

      XPath failed due to: Concatenation operator (‘||’) requires XPath 3.0 to be enabled

    • http://videlibri.sourceforge.net/cgi-bin/xidelcgi

      err:XPST0003: This language feature is not available in the selected language. At least XQuery/XPath version 3.0 is required
      in: //td[text()=”ASIN”] || [<- error occurs before here] //li[contains(., “ASIN: “)]

    • www.xpathtester.com/xpath:

      ERROR – Failed to evaluate XPath expression: javax.xml.transform.TransformerException: A location path was expected, but the following token was encountered: |

  2. Avoid common XPath version1 requirement mistakes:

    1. XPath 1.0
    2. XPath 2.0 is needed for regex, sequences.
    3. XPath 3.0 is needed for namespace literals, ||, !, inline anonymous functions.
    4. XPath 3.1 is needed for array and associative arrays.
  3. Use the (BNF) force, Luke: The above XPath versions link to the associated W3C XPath Recommendations, which include the definitive grammar rules that define legal XPath syntax. Know these well to spot/avoid XPath syntax errors.

1 XPath unfortunately has no built-in way to elicit its version. That
leaves two options: (1) know the version that the hosting language,
library, or application implements based upon its documentation, or (2) initiate a simple probe (of known
proper syntax, of course) that uses a version-specific feature and see if a syntactical is avoided.

4

solved Syntax Error: XPath Is Not a Legal Expression