XPath wildcard in attribute value

Colin Brown picture Colin Brown · Dec 23, 2011 · Viewed 24k times · Source

I have the following XPath to match attributes of the class span:

//span[@class='amount']

I want to match all elements that have the class attribute of "amount" but also may have other classes as well. I thought I could do this:

//span[@class='*amount*'] 

but that doesn't work...how can I do this?

Answer

Wayne picture Wayne · Dec 23, 2011

Use the following expression:

//span[contains(concat(' ', @class, ' '), ' amount ')]

You could use contains on its own, but that would also match classes like someamount. Test the above expression on the following input:

<root>
  <span class="test amount blah"/>
  <span class="amount test"/>
  <span class="test amount"/>
  <span class="amount"/>
  <span class="someamount"/>
</root>

It will select the first four span elements, but not the last one.