try
{
rssDoc = new XmlDocument();
// Load the XML context into XmlDocument
rssDoc.Load(rssReader);
MessageBox.Show(rssDoc.ToString());
}
catch (Exception ex)
{
errorProvider1.SetError(url, "Cannot load the RSS from this url");
}
// Loop for <rss> tag in xmldocument
for (int i = 0; i < rssDoc.ChildNodes.Count; i++)
{
// If <rss> tag found
if (rssDoc.ChildNodes[i].Name == "rss")
{
// assign the <rss> tag node to nodeRSS
nodeRss = rssDoc.ChildNodes[i];
}
}
//Loop for the <channel> tag in side <rss> tag stored in nodeRss
for (int i = 0; i < nodeRss.ChildNodes.Count; i++) <<<<<<EXCEPTION
{
// <channel> node found
if (nodeRss.ChildNodes[i].Name == "channel")
{
//assign the <channel> tag to nodeChannel
nodeChannel = nodeRss.ChildNodes[i];
}
}
上面的代码对于大多数 rss 提要都运行良好,但我在完成最后一个循环时收到空引用异常。我应该怎么做才能让它工作?
为什么要重新发明轮子?
XmlNode nodeChannel = rssDoc.SelectSingleNode("/rss/channel");
。应该做这个伎俩。(我很确定 RSS 只允许根元素内的单个channel
元素rss
。否则,请查看SelectNodes()
而不是SelectSingleNode()
。
您的循环代码不在 try 块内。你应该先改变这一点,然后你应该使用XDocument和ForEach。也看看@Michael约林写了什么。
try
{
XDocument rssDoc = new XDocument(rssReader);
foreach(var ele in rssDoc.Elemtens["rss"])
{
}
foreach(var ele in rssDoc.Elemtens["channel"])
{
}
}
catch (Exception ex)
{
errorProvider1.SetError(url, "Cannot load the RSS from this url");
}