'SelectNodes'가 NULL을 반환하면 아래의 foreach 루프에서 NullReferenceException 오류를 어떻게 catch합니까?
나는 stackoverflow에서 검색하고이 오류를 잡기 위해 사용할 수있는 null-coalescing 조건 (?? condition)에 대해 언급했지만 HTMLNode의 구문이 무엇인지 또는 그 가능성이 있는지에 대해서는 전혀 모른다.
foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodes("//a[@href]") )
{
//Do Something
}
이 루프에 대해 어떻게 NULL 예외를 제거 하시겠습니까? 아니면이 작업을 수행하는 더 좋은 방법이 있습니까?
다음은 예외를 던지는 전체 코드입니다.
private void TEST_button1_Click(object sender, EventArgs e)
{
//Declarations
HtmlWeb htmlWeb = new HtmlWeb();
HtmlAgilityPack.HtmlDocument imagegallery;
imagegallery = htmlWeb.Load(@"http://adamscreation.blogspot.com/search?updated-max=2007-06-27T10:03:00-07:00&max-results=20&start=18&by-date=false");
foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodes("//a[@imageanchor=1 or contains(@href,'1600')]/@href"))
{
//do something
}
}
if(imagegallery != null && imagegallery.DocumentNode != null){
foreach (HtmlNode link in
imagegallery.DocumentNode.SelectNodes("//a[@href]")
?? Enumerable.Empty<HtmlNode>())
{
//do something
}
}
나는 Andra의 솔루션을 확장 메소드로 만든이 작업을 꽤 많이하고있었습니다.
using HtmlAgilityPack;
namespace MyExtensions {
public static class HtmlNodeExtensions {
/// <summary>
/// Selects a list of nodes matching the HtmlAgilityPack.HtmlNode.XPath expression.
/// </summary>
/// <param name="htmlNode">HtmlNode class to extend.</param>
/// <param name="xpath">The XPath expression.</param>
/// <returns>An <see cref="HtmlNodeCollection"/> containing a collection of nodes matching the <see cref="XPath"/> expression.</returns>
public static HtmlNodeCollection SelectNodesSafe(this HtmlNode htmlNode, string xpath) {
// Select nodes if they exist.
HtmlNodeCollection nodes = htmlNode.SelectNodes(xpath);
// I no matching nodes exist, return empty collection.
if (nodes == null) {
return new HtmlNodeCollection(HtmlNode.CreateNode(""));
}
// Otherwise, return matched nodes.
return nodes;
}
}
}
용법:
using MyExtensions;
foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodesSafe("//a[@href]")) {
//Do Something
}