Handling Apostrophes in XPath Queries

Handling Apostrophes in XPath Queries

3 July 2024 Stephan Petzl Leave a comment QA


When working with Selenium and XPath, you may encounter a scenario where your element identifiers start with an apostrophe. This can lead to issues as XPath queries in Selenium do not natively support such cases. In this article, we will explore different methods to handle apostrophes in XPath queries and ensure your tests run smoothly.

Common Issues with Apostrophes in XPath

Typically, XPath queries are written using single quotes to define attribute values. However, if your attribute value starts with an apostrophe, it can break the query syntax. For example:

By identifier = By.xpath("//span[@trans=''WbOrderHeader.OneCancelsAnother']");

In this example, the identifier 'WbOrderHeader.OneCancelsAnother' starts with an apostrophe, leading to an invalid XPath query.

Solutions to Handle Apostrophes in XPath

1. Using Backslashes to Escape Apostrophes

One effective way to handle apostrophes is by escaping them with backslashes. This method ensures that the apostrophe is treated as a literal character. Here’s how you can implement it:


2. Using the concat Function

Another method is to use the concat function defined in the W3C XPath recommendation. This function concatenates strings, allowing you to include apostrophes within your XPath query:

By.xpath("//span[@trans=concat(\\\"'\\\", 'WbOrderHeader.OneCancelsAnother')]");

3. Using the contains Function

The contains function is also a viable option. It allows you to match a substring within an attribute value, avoiding the need to handle the apostrophe directly:

By identifier = By.XPath("//span[contains(@trans,'WbOrderHeader.OneCancelsAnother')]")


Handling apostrophes in XPath queries can be challenging, but with the methods outlined above, you can ensure your Selenium tests run smoothly. Whether you choose to escape apostrophes, use the concat function, or leverage the contains function, you have multiple options to address this issue effectively.

As you continue to refine your test automation strategies, consider tools like Repeato. Repeato is a no-code test automation tool for iOS and Android that simplifies the creation, execution, and maintenance of automated tests. With its ease of setup and use, Repeato can help you manage complex test scenarios, ensuring high-quality assurance for your applications.

Like this article? there’s more where that came from!