Reputation: 10015
I have an HTML, and i need to get some nodes by class. So i can't do it because
XDocument
allows), but doc.Elements()
works only if i have an id, but i haven't. So i also dunno XML path so i cannot use SelectNodes
methodmy code was
public static class HapHelper
{
private static HtmlNode GetByAttribute(this IEnumerable<HtmlNode> htmlNodes, string attribute, string value)
{
return htmlNodes.First(d => d.HasAttribute(attribute) && d.Attributes[attribute].ToString() == value);
}
public static HtmlNode GetElemenyByAttribute(this HtmlNode parentNode, string attribute, string value)
{
return GetByAttribute(parentNode.Descendants(), attribute, value);
}
public static bool HasAttribute(this HtmlNode d, string attribute)
{
return d.Attributes.Contains(attribute);
}
public static HtmlNode GetElementByClass(this HtmlNode parentNode, string value)
{
return parentNode.GetElemenyByAttribute("class", value);
}
}
but it doesn't works, because Descendants()
returns only nearest nodes.
What can I do?
Upvotes: 1
Views: 3866
Reputation: 98746
Learn XPath! :-) It's really simple, and will serve you well. In this case, what you want is:
SelectNodes("//*[@class='" + classValue + "']") ?? Enumerable.Empty<HtmlNode>();
Upvotes: 4