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>();