【发布时间】:2013-02-14 11:30:17
【问题描述】:
谁能告诉我为什么这会引发空引用异常(对象引用未设置为对象的实例)。我的代码读取一个简单的 xml 文件,然后应该将 2 个元素中的文本传递给另一个方法。但是在 foreach 循环的第一行会抛出异常:
请原谅我的无知,我是新人。 :)
private void openProjectToolStripMenuItem_Click(object sender, EventArgs e)
{
//I have to pass 'this' (which is Form1) when creating the Projects (Form2) in order for them to understand / see each other
Projects myProjects = new Projects(this);
//displays the Form 2 (called Projects)
myProjects.Show();
XmlDocument xdoc = new XmlDocument();
xdoc.Load("O:\\TestDaws\\projects.xml");
string projList = "/Projects/Project";
XmlNodeList xprojects = xdoc.SelectNodes(projList);
foreach (XmlNode xNodeName in xprojects)
{
string projectname = xNodeName.SelectNodes("/ProjectName")[0].InnerText.ToString();
string projecttype = xNodeName.SelectNodes("/ProjectType")[0].InnerText.ToString();
myProjects.buildProjectList(projectname, projecttype);
}
}
【问题讨论】:
-
在进入
foreach循环之前,是否设置了断点并检查xprojects不为空? -
你在哪里得到空值?
-
@DarthVader 来自 OP:
However the exception is thrown at the first line of the foreach loop -
我猜没有
ProjectName的标签,这是一个列表,也就是null/
标签: c#