Search code examples
c#xmlxmldocument

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


I try to use XmlDocument to load xml file. However, the codes alway return 'Object reference not set to an instance 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?


Solution

  • 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.