XPath matching issue when text contains   instead of regular space

Viewed 408

For a regular HTML

<b>WordA WordB WordC</b>

I'd use this XPath to retrieve this element.

//b[text()='WordA WordB WordC']

But I'm having the below HTML

<b>WordA&nbsp;WordB&nbsp;WordC</b>

When I'm trying to retrieve the element in this instance, the first XPath returns nothing.

//b[text()='WordA\u00a0WordB\u00a0WordC']

Above one works.

But instead of using the '\u00a0' part, is there a better way to handle this situation. Some defined function to normalize the spaces.

etc:

//b[someFunction()='WordA WordB WordC']
2 Answers

Note that \u00a0 works because your XPath expression is embedded in some host language (such as Java or Javascript) that recognizes the escape sequence uNNNN - this is being converted to an NBSP character by the containing host language, not by XPath itself. If the XPath were embedded in XML (e.g. in XSLT or XSD) you would use &#xa0; rather than \u00a0.

There's no special way of handling NBSP in XPath, but you could translate these characters to regular spaces using translate():

//b[translate(text(), '\u00a0', ' ') = 'WordA WordB WordC']

Note also that in such expressions it's usually better to use . rather than text() to access the string value of an element. This is more resilient to variations that might arise, for example one of the words being in italics, or the words being separated by comments.

I would avoid the &nbsp; characters which will make it a lot easier as follows:

//b[contains(., 'WordA') and contains(., 'WordB') and contains(., 'WordC')]

Precisely:

//b[starts-with(., 'WordA') and contains(., 'WordB') and contains(., 'WordC')]
Related