XPath: address a value by a selector that is not parent

Viewed 34

How can I address an elementy by XPath thats selector is not above it (but at the same level)?

E.g. I want to have the value of the item with name B. Not sure hot to do it because name and value are not in a parent relationship.

<root>
    <item>
        <name>A</name>
        <value>1</value>
    </item>
    <item>
        <name>B</name>
        <value>2</value>
    </item>
    <item>
        <name>C</name>
        <value>3</value>
    </item>
</root>
3 Answers

This can be done simply as following:

//item[./name='B']/value

This literally means: find item element containing a direct child with name = "B" -> find this item element direct child value.
In case name and / or value are not the direct children of item the above expression will be

//item[.//name='B']//value

Another approach, in case inside each item there is only single name and single value can be:

//item[name='B']/following-sibling::value

To extract the value of the item with name B there are multiple approaches as follows:

  • Using following:

    //item/name[text()='B']//following::value[1]
    
  • Using following-sibling:

    //item/name[text()='B']//following-sibling::value[1]
    
  • Using ancestor:

    //name[text()='B']//ancestor::item[1]//value
    
//name[text()='B']/following-sibling::value

Gets the sibling with tag value of an element name with text B

Related