deucalion0
deucalion0

Reputation: 2440

How to find an element value based on another elements attribute value in XPath

I am trying to learn XPath, and finding it difficult, as I am Googling my way through it all. Here is my XML:

<?xml version="1.0" encoding="utf-8"?>
    <details>
        <signature id="sig1">
            <name>mr. Barry Smith</name>
            <telephone type="fixed">01234 123456</telephone>
            <telephone type="mobile">071234562</telephone>
        </signature>

        <signature id="sig2">
            <name>mr. Harry Smith</name>
            <telephone type="fixed">01234 123456</telephone>
        </signature>
    </details>

How can I find the names of people who have a mobile phone, I can get either or, but not both.

I have been trying things like this:

staffdetails/signature/telephone[@type='mobile']name

Also, is there a reference guide for using XPAth, so I can easily figure out any query I wish? Using online tutorials I have found explain how XPath works, but the examples don't cover enough.

Thank you!

Upvotes: 3

Views: 4249

Answers (2)

JLRishe
JLRishe

Reputation: 101652

There's no need to use following-sibling:: or nested predicates here. Just do this:

/details/signature[telephone/@type = 'mobile']/name

Upvotes: 7

Petr Janeček
Petr Janeček

Reputation: 38414

This should work:

//signature/name[following-sibling::telephone[@type='mobile']]

It reads as:

Select any name that has a signature parent and a telephone sibling which type = mobile.

Regarding the reference, I actually learnt the most from the examples in the spec!

Upvotes: 1

Related Questions