Brian
Brian

Reputation: 467

Retrieve an xpath text contains using text()

I've been hacking away at this one for hours and I just can't figure it out. Using XPath to find text values is tricky and this problem has too many moving parts.

I have a webpage with a large table and a section in this table contains a list of users (assignees) that are assigned to a particular unit. There is nearly always multiple users assigned to a unit and I need to make sure a particular user is assigned to any of the units on the table. I've used XPath for nearly all of my selectors and I'm half way there on this one. I just can't seem to figure out how to use contains with text() in this context.

Here's what I have so far:

//td[@id='unit']/span [text()='asdfasdfasdfasdfasdf (Primary); asdfasdfasdfasdfasdf, asdfasdfasdfasdf; 456, 3456'; testuser]

The XPath Query above captures all text in the particular section I am looking at, which is great. However, I only need to know if testuser is in that section.

Upvotes: 32

Views: 100264

Answers (1)

underrun
underrun

Reputation: 6841

text() gets you a set of text nodes. I tend to use it more in a context of //span//text() or something.

If you are trying to check if the text inside an element contains something you should use contains on the element rather than the result of text() like this:

span[contains(., 'testuser')]

XPath is pretty good with context. If you know exactly what text a node should have you can do:

span[.='full text in this span']

But if you want to do something like regular expressions (using exslt for example) you'll need to use the string() function:

span[regexp:test(string(.), 'testuser')]

Upvotes: 83

Related Questions