Make Selenium Easy

XPath Method – string() – Usage in Locating Element- How it is Different From text()

Hello Folks,

In this post we are going to learn below topics:-

  1. What is string() method in XPath?
  2. What is difference between string() and text() in XPath?
  3. Usage of string() in XPath.

What is string() method in XPath?

Before learning about we will understand a term “TextNode“. We can insert text in DOM as a node using TextNode object. TextNode does not contains any tags. It contains only text.


Above example shows a single node “div” with text node “This is a simple text in the container. You can relate it with usage of text() in XPath. In fact text() is not a function. It is a node test. A node test is a condition on the name, element, attribute, text etc.

You can even locate the text as a node as shown below:-

Look at below html code:-

You can say that above html code has multiple text nodes. If you call text() on person node , it will give you all children text nodes as shown below:-

We can get a concatenated text nodes of a context node by using string() method in xpath. If we call string() method on “person” tag, it will give concatenated text node of all children i.e. “Mr. Amod Mahajan 28 Make Selenium Easy” including all whitespaces.

string() method will be very useful in writing xpath. Let’s see some scenarios:-

Scenario 1:

Suppose you need to locate a person whose age is 28. You can locate using independent dependent concept of XPath as shown below:-


Same you can do easily with string() method as shown below:-


Sceanior 2:-

Consider below html code:-

If you want to locate div with text(), it will not work:-

Try string() method here , it will work fine :-

Difference between string() and text() in XPath:

I think you must have got the difference between string() and text() above. text() is a test node while string() is a method in xpath.

About getText() method of Selenium WebDriver:-

Did you know that getText() method of Selenium WebDriver also returns you the almost same as string() in XPath. I said almost same as getText() truncates whitespaces. As per Selenium documentation:-

Sample Program:-


Amod Mahajan 28 Make Selenium Easy

Hope you learnt something new today and you will be able to utilize this method.

Share this post to your colleagues and friends to extend their knowledge.



Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

3 thoughts on “XPath Method – string() – Usage in Locating Element- How it is Different From text()

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.