簡體   English   中英

WPF異常“根元素丟失”

[英]WPF Exception “Root Element is Missing”

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

不要使用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();

根據需要處理缺失值。

請檢查您是否可以使用

SyndicationFeed類

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM