天天看點

Windows Phone 7 網絡程式設計之RSS閱讀器

實作一個RSS閱讀器,通過你輸入的RSS位址來擷取RSS的資訊清單和檢視RSS文章中的詳細内容。RSS閱讀器是使用了WebClient類來擷取網絡上的RSS的資訊,然後再轉化為自己定義好的RSS實體類對象的清單,最後綁定到頁面上。

(1) RSS實體類和RSS服務類

RssItem.cs

using System.Net;  

using System.Text.RegularExpressions;  

namespace WindowsPhone.Helpers  

{  

    /// <summary> 

    /// RSS對象類  

    /// </summary> 

    public class RssItem  

    {  

        /// <summary> 

        /// 初始化一個RSS目錄  

        /// </summary> 

        /// <param name="title">标題</param> 

        /// <param name="summary">内容</param> 

        /// <param name="publishedDate">發表事件</param> 

        /// <param name="url">文章位址</param> 

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

        {  

            Title = title;  

            Summary = summary;  

            PublishedDate = publishedDate;  

            Url = url;  

            //解析html  

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

        }  

        //标題  

        public string Title { get; set; }  

        //内容  

        public string Summary { get; set; }  

        //發表時間  

        public string PublishedDate { get; set; }  

        //文章位址  

        public string Url { get; set; }  

        //解析的文本内容  

        public string PlainSummary { get; set; }  

    }  

RssService.cs

<phone:PhoneApplicationPage   

    x:Class="ReadRssItemsSample.MainPage" 

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 

    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 

    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 

    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768" 

    FontFamily="{StaticResource PhoneFontFamilyNormal}" 

    FontSize="{StaticResource PhoneFontSizeNormal}" 

    Foreground="{StaticResource PhoneForegroundBrush}" 

    SupportedOrientations="Portrait" Orientation="Portrait" 

    shell:SystemTray.IsVisible="True"> 

    <Grid x:Name="LayoutRoot" Background="Transparent"> 

        <Grid.RowDefinitions> 

            <RowDefinition Height="Auto"/> 

            <RowDefinition Height="*"/> 

        </Grid.RowDefinitions> 

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> 

            <TextBlock x:Name="ApplicationTitle" Text="RSS閱讀器" Style="{StaticResource PhoneTextNormalStyle}"/> 

        </StackPanel> 

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> 

            <Grid.RowDefinitions> 

                <RowDefinition Height="Auto" /> 

                <RowDefinition  Height="*"/> 

            </Grid.RowDefinitions> 

            <TextBlock FontSize="30" Grid.Row="1" Height="49" HorizontalAlignment="Left" Margin="0,6,0,0" Name="textBlock1" Text="RSS位址" VerticalAlignment="Top" Width="116" /> 

            <TextBox Grid.Row="1" Height="72" HorizontalAlignment="Left" Margin="107,0,0,0" Name="rssURL" Text="http://www.cnblogs.com/rss" VerticalAlignment="Top" Width="349" /> 

            <Button Content="加載 RSS" Click="Button_Click" Margin="-6,72,6,552" Grid.Row="1" /> 

            <ListBox x:Name="listbox" Grid.Row="1" SelectionChanged="OnSelectionChanged" Margin="0,150,6,-11"> 

                <ListBox.ItemTemplate  > 

                    <DataTemplate> 

                        <Grid> 

                            <Grid.RowDefinitions> 

                                <RowDefinition Height="Auto" /> 

                                <RowDefinition Height="60" /> 

                            </Grid.RowDefinitions> 

                            <TextBlock Grid.Row="0" Text="{Binding Title}" Foreground="Blue" /> 

                            <TextBlock Grid.Row="1" Text="{Binding PublishedDate}" Foreground="Green" /> 

                            <TextBlock Grid.Row="2" TextWrapping="Wrap" Text="{Binding PlainSummary}" /> 

                        </Grid> 

                    </DataTemplate> 

                </ListBox.ItemTemplate> 

            </ListBox> 

        </Grid> 

    </Grid> 

</phone:PhoneApplicationPage> 

(2) RSS頁面展示

MainPage.xaml

using System;  

using System.Collections.Generic;  

using System.IO;  

using System.ServiceModel.Syndication;  

using System.Xml;  

    /// 擷取網絡RSS服務類  

    public static class RssService  

        /// 擷取RSS目錄清單  

        /// <param name="rssFeed">RSS的網絡位址</param> 

        /// <param name="onGetRssItemsCompleted">擷取完成事件</param> 

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

            WebClient webClient = new WebClient();  

            //注冊webClient讀取完成事件  

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

            {  

                try  

                {  

                    if (e.Error != null)  

                    {  

                        if (onError != null)  

                        {  

                            onError(e.Error);  

                        }  

                        return;  

                    }  

                    //将網絡擷取的資訊轉化成RSS實體類  

                    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);  

                    //通知完成傳回事件執行  

                    if (onGetRssItemsCompleted != null)  

                        onGetRssItemsCompleted(rssItems);  

                }  

                finally  

                    if (onFinally != null)  

                        onFinally();  

            };  

            webClient.OpenReadAsync(new Uri(rssFeed));  

MainPage.xaml.cs

using System.Windows;  

using System.Windows.Controls;  

using Microsoft.Phone.Controls;  

using WindowsPhone.Helpers;  

namespace ReadRssItemsSample  

    public partial class MainPage : PhoneApplicationPage  

        private  string WindowsPhoneBlogPosts = "";  

        public MainPage()  

            InitializeComponent();  

        private void Button_Click(object sender, RoutedEventArgs e)  

            if (rssURL.Text != "")  

                WindowsPhoneBlogPosts = rssURL.Text;  

            }  

            else  

                MessageBox.Show("請輸入RSS位址!");  

                return;  

            //加載RSS清單  

            RssService.GetRssItems(  

                WindowsPhoneBlogPosts,  

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

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

                null  

                );  

        //檢視文章的詳細内容  

        private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)  

            if (listbox.SelectedItem == null)  

            var template = (RssItem)listbox.SelectedItem;  

            MessageBox.Show(template.PlainSummary);  

            listbox.SelectedItem = null;  

(3)程式運作的效果如下

本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1078563

繼續閱讀