简体   繁体   中英

C# HTMLAgilityPack System.NullReferenceException

I can get the following to work in .Net Fiddle: https://dotnetfiddle.net/Xd8pO1

using HtmlAgilityPack;
using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var html =
        "<select class=\"vui-input d2l-select\" name=\"roleid\" id=\"z_d\" title=\"Role\"><option value=\"0\" selected=\"selected\">-- Select a Role --<option value=\"104\">Instructor<option value=\"105\">Student<option value=\"106\">TA 1<option value=\"107\">TA 2<option value=\"108\">TA 3<option value=\"109\">TA 4<option value=\"114\">TA 5<option value=\"115\">TA 6<option value=\"111\">Course Developer</select>";

        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(html);

        string name = htmlDoc.DocumentNode
                        .SelectNodes("//*[text()[contains(., 'Instructor')]]").First().Attributes["value"].Value;

        Console.WriteLine(name);
    }
}

However, it does not work when I try to run it in my .Net application or in a new console application.

I get the following error:

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=DELETE
  StackTrace:
   at Program.Main() in E:\...........:line 18

I've tested to make sure the source is correctly formatted. Replacing line 18 with the following works:

string name = `htmlDoc.DocumentNode.SelectNodes("//select/option[@value=104]")
.First()
.Attributes["value"].Value;`

Any ideas why this is working in .Net Fiddle but not in my c# application in Visual Studio?

I did some more searching and found this: HtmlAgilityPack produces missing closing tags in OuterHtml

It looks like HTMLAgilityPack had an issue with parsing tags where it removed the closing tag. I've updated my HTMLAgilityPack version to the latest and it is working now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM