xpathxpath-1.0

XPath predicate must be preceded by node test


I have read all I could find but just wanted to confirm that the following is NOT a valid XPath expression because of the reason mentioned in the title.

//trip/[@trainID]

I already found that the expression

//trip[@trainID]

Selects all trip elements with the attribute called trainID,

and that the expression

//trip/@trainID

Selects all trainID attributes on trip elements.

I also had referred to this answer.

(Reason for the question:)

I knew that the predicate (the part in square brackets) creates a filter.
I thought that maybe the expression in question would select all trainID attributes on trip elements (as shown in the third expression above) in the absence of any test on the attribute.

That did not work in my test, and as confirmed below, the expression is simply not valid.


Solution

  • No, //trip/[@trainID] is not a valid XPath.

    Like you said in the title, a predicate must be proceeded by a node test.

    From the 1.0 spec:

    [4]       Step       ::=      AxisSpecifier NodeTest Predicate*   
                                 | AbbreviatedStep
    

    With NodeTest defined as:

    [7]       NodeTest       ::=      NameTest    
                                     | NodeType '(' ')'   
                                     | 'processing-instruction' '(' Literal ')'