0

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?

3
  • Where is the xpath text? Commented Jan 15, 2014 at 18:56
  • "//[@class='value']" ? Commented Jan 15, 2014 at 19:00
  • 1
    Isn't this answered by stackoverflow.com/questions/14248063/… ? Commented Jan 15, 2014 at 19:10

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Nop, because it needs to give back nodes.
@Tommz, I was wondering that while sitting here, please see my edit.
Yepp, now it's correct, but I need to give to Heath correct answer since he answered correctly first :) Thanks a lot though.
2

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.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.