我有一個HTML,我需要按類獲取一些節點。所以我不能這樣做因為
XDocument
允許),但doc.Elements()
僅在我有id時才有效,但我沒有。所以我也不知道XML路徑,所以我不能使用SelectNodes
方法我的代碼是
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);
}
}
但它不起作用,因為Descendants()
只返回最近的節點。
我能做什麼?
學習XPath! :-)這很簡單,並且會很好地為你服務。在這種情況下,你想要的是:
SelectNodes("//*[@class='" + classValue + "']") ?? Enumerable.Empty<HtmlNode>();