Locating the node by value containing whitespaces using XPath

Depending on your exact situation, there are different XPath expressions that will select the node, whose value contains some whitespace.

First, let us recall that any one of these characters is “whitespace”:

    	 — the Tab

    
 — newline

    
 — carriage return

    ' ' or   — the space

If you know the exact value of the node, say it is “Hello World” with a space, then a most direct XPath expression:

     /top/aChild[. = 'Hello World']

will select this node.

The difficulties with specifying a value that contains whitespace, however, come from the fact that we see all whitespace characters just as … well, whitespace and don’t know if a it is a group of spaces or a single tab.

In XPath 2.0 one may use regular expressions and they provide a simple and convenient solution. Thus we can use an XPath 2.0 expression as the one below:

    /*/aChild[matches(., "Hello\sWorld")]

to select any child of the top node, whose value is the string “Hello” followed by whitespace followed by the string “World”. Note the use of the matches() function and of the “\s” pattern that matches whitespace.

In XPath 1.0 a convenient test if a given string contains any whitespace characters is:

not(string-length(.)= stringlength(translate(., ' 	

','')))

Here we use the translate() function to eliminate any of the four whitespace characters, and compare the length of the resulting string to that of the original string.

So, if in a text editor a node’s value is displayed as

“Hello    World”,

we can safely select this node with the XPath expression:

/*/aChild[translate(., ' 	

','') = 'HelloWorld']

In many cases we can also use the XPath function normalize-space(), which from its string argument produces another string in which the groups of leading and trailing whitespace is cut, and every whitespace within the string is replaced by a single space.

In the above case, we will simply use the following XPath expression:

/*/aChild[normalize-space() = 'Hello World']

Leave a Comment