AshM
AshM

Reputation: 63

XPath query that matches multiple attributes of any particular element name

Given the following sample XML:

<a z="123" y="321"></a>
<b z="456" y="654"></b>

<c x="456" w="654"></c>
<c x="123" w="111"></c>
<c x="789" w="321"></c>

I need an xpath query that will return element 'a', because there is a 'c' element whose @x equals the a's @z, and whose @w does NOT equal the a's @y.

Notice that 'b' is not returned because there is a 'c' element where @x=@z and @w=@y.

Also, the elements being returned can be any element (*). The important bit is there is a matching 'c' element, where the second attribute doesn't match.

The closest I've come up with is this:

//*[@z=//c/@x and .[@y != //c/@w]]

However in my sample above, this would not return 'a' because @z matches @x of a 'c' element, and @y matches @w of a different 'c' element. The second attribute check needs to be made against the same 'c' element.

I hope this makes sense.

Upvotes: 2

Views: 170

Answers (1)

Mads Hansen
Mads Hansen

Reputation: 66781

This XPath 2.0 expression:

//*[
    let $a := . 
    return 
     following-sibling::*[@x eq $a/@z and not(@w eq $a/@y)] 
    ]

Will bind the matched element to a variable in a predicate, and then use it in a predicate for the following-sibling elements of that context element to see if their attributes satisfy the stated requirements.

Upvotes: 1

Related Questions