XPath wildcard in attribute value

c# html-agility-pack xpath

Question

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?

Accepted Answer

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.


Popular Answer

You need to use contains method. See How to use XPath contains() here?

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




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why