在WP7阅读RSS

原文地址:http://www.codeproject.com/Articles/153472/Reading-RSS-items-on-Windows-Phone-7

下面是我写的一个帮助我在WP7中阅读RSS工具类。我将介绍如何去写并且如何使用它。

文章结束的地方可以找到一个包含所有代码的简单示例。

如何去读RSS

添加一个Helper程序集

第一步我们将添加一个程序集的引用 System.ServiceModel.Syndication.dll (包含解析RSS的类)

这个程序集属于Silverlight3 sdk,不属于Windows Phone sdk,但是在这使用它是没问题的。

你在以下路径中可以找到它:%ProgramFiles%\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\System.ServiceModel.Syndication.dll

在WP7阅读RSS

你可能会遇到以下警告,忽略继续

在WP7阅读RSS
定义 RssItem

我们需定义一个模型类来装载rss项数据

我们的RssItem类将包含以下几个属性:Title, Summary, PublishedDate and Url, PlainSummary

/// <summary>

/// Model for RSS item

/// </summary>

public class RssItem

{

    /// <summary>

    /// Initializes a new instance of the <see cref="RssItem"/>class.

    /// </summary>

    /// <param name="title">The title.</param>

    /// <param name="summary">The summary.</param>

    /// <param name="publishedDate">The published date.</param>

    /// <param name="url">The URL.</param>

    public RssItem(string title, string summary, string publishedDate, string url)

    {

        Title = title;

        Summary = summary;

        PublishedDate = publishedDate;

        Url = url;

        //Get plain text from html

        PlainSummary = HttpUtility.HtmlDecode(Regex.Replace(summary, "<[^>]+?>",""));

    }

    /// <summary>

    /// Gets or sets the title.

    /// </summary>

    /// <value>The title.</value>

    public string Title { get; set; }

    /// <summary>

    /// Gets or sets the summary.

    /// </summary>

    /// <value>The summary.</value>

    public string Summary { get; set; }

    /// <summary>

    /// Gets or sets the published date.

    /// </summary>

    /// <value>The published date.</value>

    public string PublishedDate { get; set; }

    /// <summary>

    /// Gets or sets the URL.

    /// </summary>

    /// <value>The URL.</value>

    public string Url { get; set; }

    /// <summary>

    /// Gets or sets the plain summary.

    /// </summary>

    /// <value>The plain summary.</value>

public string PlainSummary { get; set; }

}


订阅服务

RSS服务通过一个参数获得RSS URL地址。另外,我们需要定义一些委托参数去实现异步调用:

  • Action<IEnumerable<RssItem>> onGetRssItemsCompleted, RSS items准备进行处理时调用。
  • Action<Exception> onError, 在获取RSS items时发生异常调用
  • Action onFinally,不管是否有异常,它将作为作为try-catch-finally进行调用
    下面是方法签名:

public static void GetRssItems(string rssFeed,

Action<IEnumerable<RssItem>> onGetRssItemsCompleted = null,

Action<Exception> onError = null,
Action onFinally = null)


 使用 WebClient 获取 feed xml.

WebClient webClient = new WebClient();

// register on download complete event

webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)

{

    ...

};

webClient.OpenReadAsync(new Uri(rssFeed));


在我们的 helper 程序集中 , 实际上是用 SyndicationFeed 类来解析 RSS.

// convert rss result to model

List<RssItem> rssItems = new List<RssItem>();

Stream stream = e.Result;

XmlReader response = XmlReader.Create(stream);

SyndicationFeed feeds = SyndicationFeed.Load(response);

foreach (SyndicationItem f in feeds.Items)

{

   RssItem rssItem = new RssItem(f.Title.Text, f.Summary.Text,f.PublishDate.ToString(), f.Links[0].Uri.AbsoluteUri);

rssItems.Add(rssItem);}


其余的代码是处理不同的委托: onCompleted, onError and onFinally

/// <summary>

/// Gets the RSS items.

/// </summary>

/// <param name="rssFeed">The RSS feed.</param>

/// <param name="onGetRssItemsCompleted">The on get RSS items completed.</param>

/// <param name="onError">The on error.</param>

public static void GetRssItems(string rssFeed, Action<IEnumerable<RssItem>> onGetRssItemsCompleted = null, Action<Exception> onError = null, Action onFinally = null)

{

    WebClient webClient = new WebClient();

    // register on download complete event

    webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)

    {

        try

        {

            // report error

            if(e.Error != null)

            {

                if (onError != null)

                {

                   onError(e.Error);

                }

                return;

            }

            // convert rss result to model

            List<RssItem> rssItems = new List<RssItem>();

            Stream stream =e.Result;

            XmlReader response =XmlReader.Create(stream);

            SyndicationFeed feeds =SyndicationFeed.Load(response);

            foreach(SyndicationItem f in feeds.Items)

            {

                RssItem rssItem = new RssItem(f.Title.Text, f.Summary.Text, f.PublishDate.ToString(), f.Links[0].Uri.AbsoluteUri);

                rssItems.Add(rssItem);

            }

            // notify completed callback

            if(onGetRssItemsCompleted != null)

            {

               onGetRssItemsCompleted(rssItems);

            }

        }

        finally

        {

            // notify finally callback

            if(onFinally != null)

            {

                onFinally();

            }

        }

    };

webClient.OpenReadAsync(new Uri(rssFeed));

}

使用RSS 服务

使用这个服务是非常简单的,只要提供URL作为第一个参数,并且定义一个委托来处理“completed”通知.

private void Button_Click(object sender, RoutedEventArgs e)

{

    RssService.GetRssItems(

        WindowsPhoneBlogPosts,

        (items) => {listbox.ItemsSource = items; },

        (exception) => {MessageBox.Show(exception.Message); },

        null

        );

}


下面是一个简单的例子,代码下载地址 here. http://blogs.microsoft.co.il/blogs/arik/ReadRssItemsSample.zip

在WP7阅读RSS

你可能感兴趣的:(wp7)