Search code examples
c#xamarinhtml-agility-pack

Parsing html using HtmlAgilityPack in C# for a cross-platform Xamarin app


I am trying to parse an online calendar to have the events posted on that calendar display in my cross-platform app. This is the code that I have so far.

 var html = @"http://html-agility-pack.net/";
 HtmlWeb web = new HtmlWeb();
 HtmlDocument htmldoc = new HtmlAgilityPack.HtmlDocument();
 var htmlDoc = web.LoadFromWebAsync(html);
 HtmlNodeCollection node=htmlDoc.DocumentNode.SelectSingleNode("//body");

The error I am getting is:

"'Task HtmlDocument' does not contain a definition for "DocumentNode' and no extension method 'DocumentNode' accepting a first argument of type 'Task HtmlDocument' could be found (are you missing a using directive or an assembly reference?"

I installed HtmlAgilityPack using the NuGet package manager in Xamarin so it is in my references for the entire project and I am using "using HtmlAgilityPack;" I viewed the HAP in the object browser and there is clearly a "DocumentNode"property which is why I am confused as to why it doesn't think there is.

I don't know what it is that I am missing, please help.


Solution

  • you need to use await when calling an async method

    // htmlDoc is a Task<HtmlDocument>
    var htmlDoc = web.LoadFromWebAsync(html);
    
    // htmlDoc is a HtmlDocument
    var htmlDoc = await web.LoadFromWebAsync(html);