[英]WPF Exception “Root Element is Missing”
I have written code in WPF c# to get RSS Atom XML Feed but it gives an Exception that root element id missing. 我已经在WPF c#中编写代码来获取RSS Atom XML Feed,但是它提供了一个异常,即缺少根元素id。 How to solve this can you please help me. 怎么解决这个可以请你帮帮我。 My code is: 我的代码是:
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);
}
Don't use DataSet
; 不要使用DataSet
; it is very old and not intended for general-purpose XML reading. 它非常陈旧,不适用于通用XML阅读。 I recommend using LINQ to XML. 我建议使用LINQ to XML。 Something like this: 像这样的东西:
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();
Deal with missing values as you see fit. 根据需要处理缺失值。
Please check if you can use the 请检查您是否可以使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.