我有一个 HTML,我需要按类获取一些节点。所以我不能这样做,因为
- 我不知道 XML 路径
- 需要的元素没有ID,只有类
- HtmlAgilityPack 不允许获取所有元素(如
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>();
