Finding elements by XPath on Android


How do I find an element that does not use “resource-id”, or “content-desc”? I’d like to read the text of an android.widget.TextView via Appium. I can find the element by calling driver.FindElementByXPath("//android.widget.TextView[@text=‘text that is displayed’]"). But that’s not what I want to do. I want to compare the text with the expected one.

The UI Automation Viewer correctly shows the element. But the element’s absolute XPath is very long and there seems to be no tools that output absolute XPath string. I can reach some near-by elements by using the text. I’m hoping that I can reach the target element from there relatively. I tried various way to do so, but nothing was successful so far.

I would appreciate any suggestions.


OK. I was able to locate the target element by using the following code:

var grandParentElement = driver.FindElementByXPath("//android.widget.TextView[@text=‘text that is displayed’]/../..");
var targetElement = grandParentElement.FindElementByXPath("(//android.widget.TextView)[2]");

The key was the XPath syntax of the second call - I needed to enclose the element by parenthesis.