Reputation: 454
This question is quite popular, but the answers I found do not work for me.
So, I have the following code snippet:
MobileElement room = driver.findElement (By.xpath ("//android.widget.TextView[@text = 'Test Room']"));
//Doing some stuff with the room element
MobileElement roomContainer = room.findElement (By.xpath ("./.."));
I get the room
variable, do some stuff with it. Then I try to search for the parent of this element, but I get NoSuchElement
exception.
I tried different combinations of Xpath, none of them worked:
".//..", "//..", "/..", ".."
However, when I search from the driver using the whole query, it works:
driver.findElement (By.xpath ("//android.widget.TextView[@text = 'Test Room']/.."))
But in this particular case I need to search from the room
element directly. Any advice?
Upvotes: 0
Views: 6510
Reputation: 11
Try with "//.."
Example: You have child_element
your Code should looks like this:
child_element.findElement(By.xpath("//..")) should get parent
Upvotes: 0
Reputation: 585
Try using the below Xpath:
MobileElement roomContainer = room.findElement(By.xpath("./parent::android.view.ViewGroup"));
Upvotes: 1
Reputation: 2881
Although you are able to locate parents node with below xpath as per your question.
driver.findElement (By.xpath ("//android.widget.TextView[@text = 'Test Room']/.."))
But you want to locate parent node from current child node with ./..
instead writing full xpath for parent node.
We can achieve it with in reverse approach, we can write full xpath for parent and we can find child node inside parent node instead full page or DOM.
MobileElement roomContainer = driver.findElement (By.xpath ("//android.widget.TextView[@text = 'Test Room']/.."))
MobileElement room = roomContainer.findElement (By.xpath ("//android.widget.TextView[@text = 'Test Room']"));
OR
MobileElement room = roomContainer.findElement (By.id ("item_rooms_list_tv_room_name]"));
Note: Parent node also have resource id for locate but I am not sure it is unique as I can’t see other 2 viewGroup
nodes so I have used xpath for parent node.
Upvotes: 1