Question

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?

Was it helpful?

Solution

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;

OTHER TIPS

Yes, it's easy with XPath:

//*[@class='foo']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top