Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPATH: select nodes of given name which are immediately following some specific nodes

Tags:

xml

xpath

best shown by a simplified example:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <A name="wrong"></A>
    <B>not this</B>
    <A name="right">
      <subA></subA>
    </A>
    <B>yes, this</B>  <!-- I want only this one -->
    <A name="right">
      <subA></subA>
    </A>
    <C>dont want this</C>
    <B>not this either</B>  <!-- not immediately following -->
</root>

I want all <B> nodes that are immediately following an <A> node with name attribute equals "right".

What I tried:

//A[@name="right"]/following-sibling::*[1]

which selects any node immediately following the "right" <A> (i.e. including <C>). I don't see how to make it only <B>. This didn't work:

//A[@name="right"]/following-sibling::*[1 and B]

This one:

//A[@name="right"]/following-sibling::B[1]

would select the first <B> after the "right" <A>, but not necessarily the immediately following one.

like image 438
davka Avatar asked Jun 16 '11 10:06

davka


People also ask

How can we select immediate child in XPath?

The key part of this XPath is *[1] , which will select the node value of the first child of Department .

How do I find immediate parent in XPath?

Hey Hemant, we can use the double dot (“..”) to access the parent of any node using the XPath. For example – The locator //span[@id=”first”]/.. will return the parent of the span element matching id value as 'first.

Can you use XPath expression used to select the target node and its values?

XPath assertion uses XPath expression to select the target node and its values. It compares the result of an XPath expression to an expected value. XPath is an XML query language for selecting nodes from an XML. Step 1 − After clicking Add Assertion, select Assertion Category – Property Content.


1 Answers

You were nearly there:

//A[@name='right']/following-sibling::*[position()=1 and self::B]

gives exactly one node on your sample.

To refer to the element name in a condition, you need self. Simply [B] would mean an element with text exactly equal to B.

like image 115
AakashM Avatar answered Sep 19 '22 21:09

AakashM