0

I am using HTMLAgility to parse HTML document. I want to get all the images tag within the html document. Here is my code.

In some case, I am getting "imgs.Count" equals to 4. But I get an error saying 'Error: Object reference not set to an instance of an object'.

    var imgs = document.DocumentNode.SelectNodes("//img");
    if (imgs != null)
    {
        Console.WriteLine("imgs_count" + imgs.Count);
        foreach (var img in imgs) {
            var w = img.Attributes["width"].Value;
            var h = img.Attributes["height"].Value;
            Console.WriteLine("w=" + w + " h=" + h);
        }
    }

When I look at my source, it does have 4 image tag. So why I am getting the error saying object reference not set?

Alexei Levenkov
  • 94,391
  • 12
  • 114
  • 159
n179911
  • 17,581
  • 40
  • 105
  • 153
  • Your object reference error is occurring when you get the `Value` of the width and height attributes. Those are not required for `img` tags, and one or the other are not present in one of the nodes. – Keith Payne Sep 25 '14 at 18:40
  • Likely one of attributes missing from HTML. See duplicate on debugging steps. Note that without sample HTML there is no other suggestion possible except making this duplicate of "null ref exception" one. – Alexei Levenkov Sep 25 '14 at 18:54

0 Answers0