Come posso rilevare l' errore NullReferenceException nel ciclo foreach qui sotto se 'SelectNodes' restituisce NULL ?
Ho cercato su StackOverflow e ho trovato menzione della condizione a coalescenza nulla (condizione) che può essere utilizzata per rilevare questo errore, tuttavia, non ho idea di quale sarebbe la sintassi per HTMLNode, o se ciò è possibile.
foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodes("//a[@href]") )
{
//Do Something
}
Come aggireresti NULL EXCEPTION per questo ciclo, o c'è un modo migliore per farlo?
Ecco il codice completo che lancia l'eccezione -
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
}
}
Lo stavo facendo alcune volte così ho reso la soluzione di Andras un metodo di estensione:
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;
}
}
}
Uso:
using MyExtensions;
foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodesSafe("//a[@href]")) {
//Do Something
}