0
            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 异常。我应该怎么做才能让它工作?

4

2 回答 2

0

您的循环代码不在 try 块内。您应该首先更改它,然后您应该使用 XDocument 和 ForEach。还可以看看@Michael Kjö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");
}
于 2012-11-22T15:14:01.253 回答
0

为什么要重新发明轮子?

XmlNode nodeChannel = rssDoc.SelectSingleNode("/rss/channel");

......应该做的伎俩。(我很确定 RSS 只允许channelrss元素内的单个元素。否则,请查看SelectNodes()而不是SelectSingleNode().)

于 2012-11-22T15:14:08.380 回答