Xpath usage on an AndroidElement

Hi all! This is a question using Java syntax and APIs, but I’m sure the core of the question will apply equally well to all supported languages.

I remember searching by Xpath a long time ago on WebElements (more specifically, they are MobileElements, but all MobileElement types extend from WebElement). For example, I retrieved an AndroidElement like so:

AndroidElement myElement = driver.findElement(Some locator);

I then tried to search for descendant elements of myElement using Xpath by passing in an Xpath locator to the AndroidElement’s findElement method:

myElement.findElement(By.xpath("//android.widget.TextView"));

I remember that this operation was not supported, and I probably got some exception. However, quite a long time has passed since I tried doing something like this, and I’m wondering if the current Appium supports searching by Xpath with a given element as the root. It would be neat to be able to set the search scope to be only children of a particular element without having to specify an Xpath to specify the ancestor element each time.

I’ll test this out over this weekend as well to see what’s up, but if anyone knows about this already, it would be neat to know quickly!

It’s also possible my Xpath syntax may be wrong. If it is, definitely point it out.

So, after a bit of research, I don’t think Xpath used on a given element will work. I also wanted to test if calling a method on a MobileElement would lead to some exception being thrown if the view was off the screen, so I came up with the following test:

  1. Create a sample Android test application. The test application’s UI is composed of a ListView with data elements 0…99.
  2. In the Appium portion of the test, find some way to retrieve a MobileElement representing the ListView.
  3. Use the Xpath expression “child::*” on the ListView MobileElement’s findElementsByXpath method.
  4. Retrieve the first child of the list view using whatever method.
  5. Scroll the list view so the first child is off the screen.
  6. Call getText, getLocation, and getSize on the first child’s MobileElement after scrolling it off screen.

Interestingly, there will be no result found from step 3, even though the list view definitely contains children (as verified by uiautomatorviewer).

Step 6 will also work perfectly fine. In this case, getText, getLocation, and getSize will return the values for the current first child of the list view. This means that at the start of the test, the first child is 0. After scrolling this text view off screen, the first child might be something like 13. Step 6 will return values for the text view containing the text “13”, and will not throw an exception or an error.