James Taylor
James Taylor

Reputation: 93

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.

Upvotes: 0

Views: 352

Answers (1)

Daniel Haley
Daniel Haley

Reputation: 52848

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

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

Upvotes: 2

Related Questions