0

I am stuck in a situation where I want to write Xpath dynamically in the properties file. The actual XPath is like in property File div[contains(text(),'<state Name>')]. State Name changes everytime. How can I write dynamic xpath which fetches from property file?

below is Xpath stored in properties file

data=div[contains(text(),'New Delhi')]

and below code snippet is fetching xpath in test script

String checkCity=prop.getProperty(data) ; 
WebElement xpath = driver.findElement(By.xpath(prop.getProperty(locatorKey)));
1

You can use the String replace method.

String city            = prop.getProperty("data"); // New Delhi
String locatorTemplate = prop.getProperty("locatorKey"); // div[contains(text(),'<state Name>')]
String locator         = locatorTemplate.replace(locatorPattern, city); // div[contains(text(),'New Delhi')]
WebElement element     = driver.findElement(locator);

locatorPattern in your case would be <state Name>.

The method syntax is as follows:

public String replace(char searchChar, char newChar)
1

You create a string

String cityName = "London";
String data = "div[contains(text(),"+ "'"+cityName +"'"+")]";
System.out.println(data);

You can put in a for loop and then use this data value as locator.

0

I'm going to skip the reading from properties file part, since you seem to have figured it out.

Let's say you have

String data = "div[contains(text(),'New Delhi')]";

You can use Java's split() method to split that string with ' as the delimiter:

a.split("'")

And then take the second element of the resulting array:

a.split("'")[1]

So

System.out.println(a.split("'")[1]);

will print out "New Delhi" to console.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.