The SyndicationFeed class in Silverlight makes it easy to parse the feed response. The process of reading a feed is as simple as reading a RSS feed using the WebClient class, loading the stream into the SyndicationFeed class and binding it to the Silverlight UI.
To use the SyndicationFeed class you need to add reference to System.ServiceModel.Syndication
The steps are as follows,
To use the SyndicationFeed class you need to add reference to System.ServiceModel.Syndication
The steps are as follows,
1.) In the code displayed below, a LoadRSS() method is created where the WebClient object, adds the handler and initiates the request. To request a resource as a stream, you must call an OpenReadAsync method overload.
protected void LoadRSS(string uri)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted +=new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
Uri feedUri = new Uri(uri, UriKind.Absolute);
wc.OpenReadAsync(feedUri);
}
{
WebClient wc = new WebClient();
wc.OpenReadCompleted +=new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
Uri feedUri = new Uri(uri, UriKind.Absolute);
wc.OpenReadAsync(feedUri);
}
2.) In the wc_OpenReadCompleted callback function, we check the Error property for errors. If there aren't any, we use the XMLReader class to read the RSS xml and then load the Syndication Feed from the reader.
private void wc_OpenReadCompleted(object sender,
OpenReadCompletedEventArgs e)
{
if (e.Error != null)
{
txtFeedLoc.Text = "Error reading feed. Try Again later.";
return;
}
using (Stream s = e.Result)
{
SyndicationFeed feed;
List feedItems = new List();
using (XmlReader reader = XmlReader.Create(s))
{
feed = SyndicationFeed.Load(reader);
foreach (SyndicationItem feedItem in feed.Items)
{
feedItems.Add(feedItem);
}
var posts = from item in feedItems
select new RSSFeed()
{
Title = item.Title.Text,
NavURL = item.Links[0].Uri.AbsoluteUri,
Description = item.Summary.Text
};
dGrid.ItemsSource = posts;
dGrid.Visibility = Visibility.Visible;
}
}
}
3.) An RSSFeed class (see code below) is created to store some properties of the RSS. Then LINQ is used to loop through the items collection of SyndicationFeed and set the properties of the RSSFeed class. The DataGrid is then bound to the collection.
public class RSSFeed
{
public string Title { get; set; }
public string NavURL { get; set; }
public string Description { get; set; }
}
0 comments:
Post a Comment