'How to construct the By.xpath method for customized locators?

I'm trying to use the By method for the setting of variables in my page object class. One of my scenario requires the table to loop with customized value based on user input.

So I had to write customized xpath. But when trying to write to fit into the By method i'm stuck on how to handle the iteration number. For example the below shows my locator:

By test = By.xpath("//thead/tr[1]/th[" + i + "]"));

It shows error for the "i" value in the declaration, even if int i ; is declared.

Please let me know how to handle this.



Solution 1:[1]

As the variable i is of type integer, you have to convert it into a string before constructing the effective locator strategy as follows:

By test = By.xpath("//thead/tr[1]/th[" + toString(i) + "]"));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1