XPath - How to select node that has only 1 class?

.net c# html-agility-pack xml xpath

Question

For xpath on c#, how can I select a node by class where the node only has that 1 class?

For example, if I had this:

<span class="red blue"></span>
<span class="red"></span>

The xpath expression given "red" will only return the second node.

Thanks.

Popular Answer

If you'd like to select all span elements that have a @class that contains red and you are sure that the string red will not appear elsewhere in the @class use this in XPATH 1.0:

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

If red may appear within a different class (like say centered) you'll need to get more complex

//span[contains(concat(' ', normalize-space(@class), ' '), ' red ')]

If you can use XPATH 2.0, you can account for both cases like this:

//span[tokenize(@class,'\s+')[. eq 'red']]



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