Some of your images do not have alt
attribute. Check if it is null.
var alt = imageNode.Attributes["alt"];
if(alt!=null)
{
var something = alt.Value;
}
Question
I'm trying to extract two attributes from one img node but there is a NullReferenceException
, the highlighted line isn't working and i can't figure out why:
var imageCollection = doc.DocumentNode.Descendants("img");
foreach (HtmlNode imageNode in imageCollection)
{
var imageLink = imageNode.Attributes["src"].Value;
var something=imageNode.Attributes["alt"].Value; // !!!
if (Regex.IsMatch(imageLink, "1280.jpg"))
{
urls.Add(imageLink);
//Date.Add(something);
}
}
and the html code:
<img src="imageurl" alt="http://bbc.in/ZWwFHt" width="610" height="610">
Solution
Some of your images do not have alt
attribute. Check if it is null.
var alt = imageNode.Attributes["alt"];
if(alt!=null)
{
var something = alt.Value;
}