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提要但我在进行最后一个循环时遇到了nullrefrence异常。 我该怎么做才能让它发挥作用?
答案 0 :(得分:0)
您的循环代码不在try块内。您应该首先更改它,然后您应该使用XDocument和ForEach。另外看看@MichaelKjörling所写的内容。
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");
}
答案 1 :(得分:0)
为什么重新发明轮子?
XmlNode nodeChannel = rssDoc.SelectSingleNode("/rss/channel");
......应该做的伎俩。 (我很确定RSS只允许在根channel
元素中使用单个rss
元素。否则,请查看SelectNodes()
而不是SelectSingleNode()
。)