WPF异常“根元素丢失”

时间:2013-10-30 17:04:31

标签: c# .net wpf rss

我已经在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);
}

2 个答案:

答案 0 :(得分: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();

根据需要处理缺失值。

答案 1 :(得分:1)

请检查您是否可以使用

SyndicationFeed class