Pranay Aitha
Pranay Aitha

Reputation: 1

Select Xpath element value based on value of another element

I am trying to capture a value using XPath based on value of a different field.

Example XML:

<?xml version="1.0" encoding="UTF-8" ?>
<employees>
    <employee>
        <id>1</id>
        <firstName>Tom</firstName>
        <lastName>Cruise</lastName>
        <photo>https://jsonformatter.org/img/tom-cruise.jpg</photo>
    </employee>
    <employee>
        <id>2</id>
        <firstName>Maria</firstName>
        <lastName>Sharapova</lastName>
        <photo>https://jsonformatter.org/img/Maria-Sharapova.jpg</photo>
    </employee>
    <employee>
        <id>3</id>
        <firstName>Robert</firstName>
        <lastName>Downey Jr.</lastName>
        <photo>https://jsonformatter.org/img/Robert-Downey-Jr.jpg</photo>
    </employee>
</employees>

I am trying to get Xpath expression for value in the firstName field, when id value is 3.

Upvotes: 0

Views: 154

Answers (1)

Prophet
Prophet

Reputation: 33381

You can locate parent node based on the known child node and then find the desired child node of that parent, as following:

//employee[./id='3']/firstName

the expression above will give the desired firstName node itself.
To retrieve it's text value this can be used:

//employee[./id='3']/firstName/text()

Upvotes: 1

Related Questions