A
A
Alexey Smirnov2016-02-16 00:56:55
HTML
Alexey Smirnov, 2016-02-16 00:56:55

How to solve the problem with the error: "Object reference does not point to an instance of an object"?

I do HTML parsing using HtmlAgilityPack.
Wrote the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml;
using System.IO;
using HtmlAgilityPack;

namespace ConsoleParsingHTMLwithHtmlAgilityPack_CSarp
{
    class Program
    {
        static void Main(string[] args)
        {
            string pathToHtml = "C:/Users/alex/Desktop/view-source_gtmarket.ru_news_2015_04_24_7130.html";
            System.IO.StreamReader HtmlDoc = new System.IO.StreamReader(pathToHtml);
            string content = HtmlDoc.ReadToEnd();
            HtmlDoc.Close();

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(content);

            var x = doc.DocumentNode.SelectNodes("//table[@class='table-data']").Elements("tr").ToList();


            foreach (HtmlNode node in x)
            {
                var s = node.Elements("td").ToList();
                foreach (HtmlNode item in s)
                {
                    Console.Write("  " + item.InnerText);
                }
                Console.WriteLine();
            }
            Console.ReadLine();

        }
    }
}

When trying to execute the program code, an error appears: "Object reference does not point to an instance of an object", at the line:
var x = doc.DocumentNode.SelectNodes("//table[@class='table-data']").Elements("tr").ToList();

What is the reason for this error, or how to solve it?
PS The HTML code for parsing was taken from here: gtmarket.ru/news/2015/04/24/7130

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2016-02-16
@ERAFY

First, break this line and see where the error shows up.

var docNode = doc.DocumentNode;
var tables = docNode.SelectNodes("//table[@class='table-data']");
var trs = tables.Elements("tr");
var trList = trs.ToList();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question