开发者

Why the codes return 'Object reference not set to an instance of an object' error?

开发者 https://www.devze.com 2023-04-04 14:02 出处:网络
I try to use XmlDocument to load xml file. However, the codes alway return \'Object reference not set to an in开发者_StackOverflow社区stance of an object\' error.

I try to use XmlDocument to load xml file. However, the codes alway return 'Object reference not set to an in开发者_StackOverflow社区stance of an object' error.

namespace TestP2
{
class Program
{
    static void Main()
    {
        XmlDocument xd = new XmlDocument();
        xd.Load(@"c:\1\1.xml");

        XmlNodeList nodelist = xd.SelectNodes("E1/E2/E3");
        foreach (XmlNode node in nodelist)
        {
            string test = "";
            test += node.Attributes.GetNamedItem("function").Value;
            Console.WriteLine(test);
        }
    }
}
}

How could I resolve this issue?


This code has vulnerability all over it, and without any other explanation, any of these could be the cause.

  1. Does xd.SelectNodes("E1/E2/E3") return a value? If it returns null, the foreach statement is going to throw the exception.
  2. Is node.Attributes.GetNamedItem("function") returning null in any situation? If so, then when you request .Value, it will throw the exception.


Your 'codes' do that because there is an object reference to something that doesnt exists. You can resolve this by debugging, and checking which object refers to this non-existing object.

In the case of XML, its very likely that nodes or attributes couldnt be found. However without the complete error message and XML its impossible to solve this issue for you.


I am suspecting the .Value might be null or not initialized. Please check your stack trace and verify.

0

精彩评论

暂无评论...
验证码 换一张
取 消