Home > Software engineering >  Appium NOT locating element when java variable is used in xpath
Appium NOT locating element when java variable is used in xpath

Time:01-23

I'm trying to locate elements dynamically usign the xpath. However, when I use variable in the xpath, elements are NOT located. However, if I use hardcoded value, elements are located properly.

What am I missing here?

Below xpath locates the elements perfectly:

driver.findElements(By.xpath("//XCUIElementTypeStaticText[contains(@value, 'hp')]"));

whereas, below xpath doesn't locate the elements:

driver.findElements(By.xpath("//XCUIElementTypeStaticText[contains(@value, '" device "')]"));

Please note that , there are multiple elements matching the above xpath.

I even tried below code but of no use:

driver.findElements(By.XPath(String.Format("//XCUIElementTypeStaticText[contains(@value, '{0}')]", device)));

Any help would be appreciated.

CodePudding user response:

Try do debug this issue as following:
Define the XPath string before calling driver.findElements method, format the string to have the proper value and then pass it into Selenium method, as following:

String xpathLocator = "//XCUIElementTypeStaticText[contains(@value, '%s')]";
xpathLocator = String.format(xpathLocator, device);
driver.findElements(By.xpath(xpathLocator));

As about your existing code.
Here driver.findElements(By.xpath("//XCUIElementTypeStaticText[contains(@value, '" device "')]"));
I can't see the formatting action.
And here driver.FindElements(By.XPath(string.Format("//XCUIElementTypeStaticText[contains(@value, '{0}')]", device)));
it seems to be a wrong syntax.
It should be String.format while you wrote string.Format

CodePudding user response:

Try trimming the spaces as:

driver.findElements(By.xpath("//XCUIElementTypeStaticText[contains(@value, '" device "')]"));

Or using String.format() as:

String device = "hp";
driver.findElements(By.XPath(String.format("//XCUIElementTypeStaticText[contains(@value, '%s')]", device)));

Note:

  1. Instead of FindElements() it should be findElements()
  2. Instead of String.Format() it should be String.format()

CodePudding user response:

The issue was with the case mismatch in the value returned by variable. i.e; device variable was returning 'hP' instead of 'hp'.

Corrected the code and it works fine now.

  • Related