Blake French
Blake French

Reputation: 53

Finding XML element using name under other parent using XPath only

I need to get a value from an XML sheet that depends on its name, which has a different parent node. In the example below, let's say I want to pull the value of "b", which is 2. How can I dynamically get a value based on its name with a XML structure like below, using only XPaths? I have no control on the format of the incoming XML, and I have limited functionality to read it, which is why I'd like to stick with XPaths if possible.

<Data>
    <Names>
        <Name>a</Name>
        <Name>b</Name>
        <Name>c</Name>
        <Name>d</Name>
    </Names>
    <Values>
        <Value>1</Value>
        <Value>2</Value>
        <Value>3</Value>
        <Value>4</Value>
    </Values>
</Data>

Upvotes: 0

Views: 56

Answers (1)

splash58
splash58

Reputation: 26153

Find needed node Name, count nodes Name before and get Valueon the same position

/Data/Values/Value[position() = count(/Data/Names/Name[.="b"]/preceding-sibling::Name)+1]

Upvotes: 2

Related Questions