2

I'm accessing this method using WPF. I know that when accessing objects from an outside method, I should use a Dispatcher. Or the "node" is a local variable and it is giving me:

Object reference not set to an instance of an object.

Why?

Here's the Code:

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);
}
Ziad Akiki
  • 2,601
  • 2
  • 26
  • 41
  • Is `xmlNews` assigned to anything? The same goes for `valery` – JMK Jul 26 '12 at 11:58
  • XmlDocument xmlNews = new XmlDocument(); SpeechSynthesizer valery = new SpeechSynthesizer(); – Ziad Akiki Jul 26 '12 at 11:59
  • 3
    `valery` could be null, `xmlNews` could be null and the result of `node.SelectSingleNode` could be null. If I'm being honest I suspect the last one, which means the attempted call to `InnerXml` is triggering the exception. – Adam Houldsworth Jul 26 '12 at 12:00

2 Answers2

2

If I'm being honest I suspect node.SelectSingleNode is returning null, which means the attempted call to InnerXml is triggering the exception.

Try making the following changes:

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);
}

I put the check on InnerXml as well just in case Speak cannot take null strings.

I don't initially suspect the XPath because those methods will return empty collections instead of null items if the XPath doesn't find anything.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
  • You were right! node.SelectSingleNode is returning null i changed the code to foreach (XmlNode node in xmlNews.SelectNodes("/rss/channel/item/title")) and it works like I wanted! Thanks! – Ziad Akiki Jul 26 '12 at 12:09
0

Take out your forward slash and try again. See below:

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);
}

This worked for me

JMK
  • 27,273
  • 52
  • 163
  • 280