html agility pack Object reference not set to an instance of an object

asp.net-web-api c# html-agility-pack

Question

I use HTML Agility Pack to parse html, and it's great stuff, however I ran into some problems. This is my background code.

public static HtmlDocument GetXHtmlFromUri2(string uri)
    {
        HttpClient client = HttpClientFactory.Create(new CustomeHeaderHandler());


        var htmlDoc = new HtmlDocument()
                                   {
                                       OptionCheckSyntax = true,
                                       OptionFixNestedTags = true,
                                       OptionAutoCloseOnEnd = true,
                                       OptionReadEncoding = true,
                                       OptionDefaultStreamEncoding = Encoding.UTF8,
                                   };

        htmlDoc.LoadHtml(client.GetStringAsync(uri).Result);

        return htmlDoc;

    }

For WebApi (Mvc4), I use HTML Agility, and this is Get Method Logic.

//GET api/values
    public string GetHtmlFlights()
    {

        var result = ClientFlightTabale.GetXHtmlFromUri2("http://ikiafids.ir/departureFA.html");
        HtmlNode node = result.DocumentNode.SelectSingleNode("//table[1]/tbody/tr[1]");

        string temp = node.FirstChild.InnerHtml.Trim();

        return temp;

    }

However, when I called this function from the browser and fiddler, I ran across errors with the same theme:

This error and object reference not assigned to an instance of an object is worried about this line

string temp = node.FirstChild.InnerHtml.Trim();

Please, if someone can assist me.

1
1
11/22/2012 9:41:03 PM

Accepted Answer

I believe you are seeking something along these lines:

var result = ClientFlightTabale.GetXHtmlFromUri2("http://ikiafids.ir/departureFA.html");
var tableNode = result.DocumentNode.SelectSingleNode("//table[1]");

var titles = tableNode.Descendants("th")
                    .Select(th => th.InnerText)
                    .ToList();

var table = tableNode.Descendants("tr").Skip(1)
                    .Select(tr => tr.Descendants("td")
                                    .Select(td => td.InnerText)
                                    .ToList())
                    .ToList();
3
11/22/2012 11:28:04 PM

Popular Answer

I believe your choice is in error. Try this in its place,

result.DocumentNode.SelectSingleNode("//table/tr[1]")


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow