我正在使用 WPF 访问此方法。我知道当从外部方法访问对象时,我应该使用调度程序。或者“节点”是一个局部变量,它给我:
Object reference not set to an instance of an object.
为什么?
代码如下:
SpeechSynthesizer valery = new SpeechSynthesizer();
XmlDocument xmlNews = new XmlDocument();
xmlNews.Load(string.Format("http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&topic=tc&output=rss"));
foreach (XmlNode node in xmlNews.SelectNodes("/rss/channel/item"))
{
valery.Speak(node.SelectSingleNode("/title").InnerXml);
}
最佳答案
老实说,我怀疑 node.SelectSingleNode
返回 null,这意味着尝试调用 InnerXml
正在触发异常。
尝试进行以下更改:
foreach (XmlNode node in xmlNews.SelectNodes("/rss/channel/item"))
{
var titleNode = node.SelectSingleNode("/title");
if (titleNode != null && !string.IsNullOrEmpty(titleNode.InnerXml))
valery.Speak(titleNode.InnerXml);
}
我也对 InnerXml
进行了检查,以防 Speak
无法采用空字符串。
我最初并不怀疑 XPath,因为如果 XPath 找不到任何内容,这些方法将返回空集合而不是 null 项。
关于c# - WPF:未将对象引用设置为对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11668759/