views:

289

answers:

3

Is there a way to build a XPath query that finds a node at a certain position AND with a certain attribute value?

Consider the following sample xml:

<Item Type="Book">
<!--1st Param node in a Book item is always the autors last name-->
<Param Value="Updike" />
<!--2nd Param node in a Book item is always the autors first name-->
<Param Value="John" />
<!--3rd Param node in a Book item is always the book title-->
<Param Value="Toward the End of Time" /></Item>

Now can I build a single query that finds the following:

Find all Item nodes of Type "Book" where the 2nd Param node has a Value of "John". So I would like to find all books where the authors frist name is "John".

Note that I am using .NET XPathDocument.

+2  A: 

Note that I am using .NET XPathDocument.

So limited to XPath V1.

You can include (relative and absolute) paths in a predicate. So something like:

//Item[@Type='Book'][./Param[2][@Value = 'John']]

(I would try and avoid "//", as it requires a search of the whole DOM, but can't provide a better axis without more context.)

Richard
Your expression is not limited to books.
Ben Blank
@Ben: Now fixed.
Richard
A: 

The expression would be:

//Item/Param[2][@Value='John']
mjmarsh
+4  A: 

What about the requirement to have only the Item that are Books?

Try this:

/Item[@Type='Book'][Param[2][@Value='John']]
jeremy