views:

198

answers:

2

I am using an XmlDocument to parse and manipulate an XHTML string, converting some nodes to non-HTML nodes.

What is the best way to get a list of all nodes with a given class name? Can it be done with XPath?

+1  A: 

With a given class? If it is just the one class, then you should be able to do something like .SelectNodes("//*[@class='foo']"). If it isn't xhtml, then the HTML Agility Pack is worth looking at.

At the client, jQuery would be a good option - and supports composite class names.

If you have multiple class names on individual elements, and need to handle it at the server, I expect you might need to find the candidate classes first ("//*[@class!='']), and then loop over them doing a Split() and checking for the class-name in the results; i.e. pull it apart manually.

In LINQ terms, something like:

        var qry = from XmlElement el in d.SelectNodes("//*[@class!='']")
                  let classes = el.GetAttribute("class").Split(new[] {' '},
                          StringSplitOptions.RemoveEmptyEntries)
                  where classes.Contains("foo")
                  select el;
Marc Gravell
I take it then that XPath does not support regular expressions?
tpower
Not natively. There are a range of string functions available to you in xpath - however, nothing that would be particularly convenient.
Marc Gravell
A: 

Yes, it's easy with XPath:

//*[@class='foo']
Jon Skeet
Thanks, does this take into account that an element can have more than one class name?
tpower