Reputation: 3453
I want to select nodes which have attribute class with some value not specifying tag.
How to do it?
So far I have:
html.DocumentNode.SelectNodes("//[@class='value']");
But it's not working good as far as I see it.
For instance, let me have this kind of HTML code:
<div>
<div class="value"></div>
<a class="value"></div>
</div>
it would need to give me back those 2 elements inside of <div>
, so <div>
and <a>
. Is that possible?
Upvotes: 0
Views: 219
Reputation: 101652
Because you're working with HTML class attributes here, I suggest using the following:
//*[contains(concat(' ', @class, ' '), ' value ')]
Note the spaces surrounding the value. This will ensure that you find the elements even if they have multiple classes. Simply using @class='value'
would not work in that situation.
Upvotes: 1
Reputation: 67898
So I believe the correct syntax for what you want is this:
html.DocumentNode.SelectNodes("//*[@class='value']");
When you're looking for just the attribute you don't need the [ ]
because you're not refining it by element.
Upvotes: 3
Reputation: 3292
If you want to include the root node, you can use the descendant-or-self
access like so:
descendant-or-self::*[@class='value']
Eliminate -or-self
if you don't want to consider the root node. More importantly, the asterisk is what is telling the XPath parser to return a node set.
Upvotes: 2