Home > Blockchain >  XPath: address a value by a selector that is not parent
XPath: address a value by a selector that is not parent

Time:01-03

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>

CodePudding user response:

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

CodePudding user response:

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

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

  • Related