为什么代码返回“对象引用未设置到对象的实例”?错误?
我尝试使用xmldocument加载XML文件。但是,代码始终返回对象引用未设置为对象的实例”错误。
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);
}
}
}
}
我该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这段代码到处都有漏洞,如果没有任何其他解释,这些都可能是原因。
xd.SelectNodes("E1/E2/E3")
返回值吗?如果它返回 null,则foreach
语句将引发异常。node.Attributes.GetNamedItem("function")
在任何情况下都会返回 null 吗?如果是这样,那么当你请求.Value
时,它会抛出异常。This code has vulnerability all over it, and without any other explanation, any of these could be the cause.
xd.SelectNodes("E1/E2/E3")
return a value? If it returns null, theforeach
statement is going to throw the exception.node.Attributes.GetNamedItem("function")
returning null in any situation? If so, then when you request.Value
, it will throw the exception.您的“代码”会这样做,因为存在对不存在的东西的对象引用。您可以通过调试并检查哪个对象引用该不存在的对象来解决此问题。
对于 XML,很可能找不到节点或属性。但是,如果没有完整的错误消息和 XML,就不可能为您解决此问题。
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.
我怀疑 .Value 可能为空或未初始化。请检查您的堆栈跟踪并验证。
I am suspecting the .Value might be null or not initialized. Please check your stack trace and verify.