Search code examples
xpathxpathdocument

XPath query that respect node positon and attribute value


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.


Solution

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