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)));

3 Answers 3


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)

You create a string

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

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


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:


And then take the second element of the resulting array:




will print out "New Delhi" to console.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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