'How to select the first element with a specific element using XPath

I need to do something similar to this:

How to select the first element with a specific attribute using XPath

Instead of evaluating the attribute content, I need to evaluate the child element value. Let's say the value is in the field book and I have to select the category node containing a specific book value. I tried this but with no success.

/bookstore/category[//book/text()='A2']

This is the source document.

<bookstore>
    <category>
        <book>A1</book>
        <book>A2</book>
    </category>
    <category>
        <book>B1</book>
        <book>B2</book>
    </category>
</bookstore>

I need my xpath expression to return only the category with book=A2 but now it returns both category nodes.



Solution 1:[1]

The issue with your xpath is that //book is selecting all book elements.

Try this instead: /bookstore/category[book='A2']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Haley