0

我已经在 WPF c# 中编写了代码来获取 RSS Atom XML Feed,但它给出了一个根元素 id 缺失的异常。如何解决这个问题你能帮我吗。我的代码是:

try
{

  string url = @"http://myweblink/newlink.xml";
  string username = "";
  string password = "";

  Uri uri = new Uri(url);
  HttpWebRequest rssFeed = (HttpWebRequest)WebRequest.Create(uri);
  rssFeed.Method = "GET";
  rssFeed.Credentials = new NetworkCredential(username, password);
  using (DataSet rssData = new DataSet())
  {
    //read the xml from the stream of the web request
    rssData.ReadXml(rssFeed.GetResponse().GetResponseStream());

    //loop through the rss items in the dataset 
    //and populate the list of rss feed items
    foreach (DataRow dataRow in rssData.Tables["item"].Rows)
    {
      newlistt.Add(new RssFeedItem
      {
        ChannelId = Convert.ToInt32(dataRow["channel_Id"]),
        Description = Convert.ToString(dataRow["description"]),
        ItemId = Convert.ToInt32(dataRow["item_Id"]),
        LinkURL = Convert.ToString(dataRow["link"]),
        PublishDate = Convert.ToDateTime(dataRow["pubDate"]),
        Title = Convert.ToString(dataRow["title"])
      });
    }
  }    
}

catch (Exception ee)
{
  MessageBox.Show(ee.Message);
}
4

1 回答 1

1

不要使用DataSet; 它非常古老,不适合通用 XML 阅读。我推荐使用 LINQ to XML。像这样的东西:

var feed = XDocument.Load(rssFeed.GetResponse().GetResponseStream());
var ns = feed.Root.Name.Namespace;
var items = (from e in feed.Root.Elements(ns + "item")
             select new RssFeedItem
                        {
                            ChannelId = (int?)e.Element(ns + "channel_Id") ?? -1,
                            Description = (string)e.Element(ns + "description"),
                            // ...
                        }).ToList();

处理您认为合适的缺失值。

于 2013-10-30T17:19:17.747 回答