天天看点

上接稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据

2、调用 REST 服务,返回 XML 数据

REST.cs(WCF创建的REST服务)

using System; 

using System.Linq; 

using System.Runtime.Serialization; 

using System.ServiceModel; 

using System.ServiceModel.Activation; 

using System.ServiceModel.Web; 

using System.Collections.Generic; 

using System.Text; 

using System.IO; 

/// <summary> 

/// 提供 REST 服务的类 

/// 注:Silverlight只支持 GET 和 POST 

/// </summary> 

[ServiceContract] 

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 

public class REST 

        /// <summary> 

        /// 用于演示返回 XML(对象) 的 REST 服务 

        /// </summary> 

        /// <param name="name"></param> 

        /// <returns></returns> 

        [OperationContract] 

        [WebGet(UriTemplate = "User/{name}/xml", ResponseFormat = WebMessageFormat.Xml)] 

        public User HelloXml(string name) 

        { 

                return new User { Name = name, DayOfBirth = new DateTime(1980, 2, 14) }; 

        } 

        /// 用于演示返回 XML(集合) 的 REST 服务 

        [WebGet(UriTemplate = "Users/xml", ResponseFormat = WebMessageFormat.Xml)] 

        public List<User> HelloXml2() 

                return new List<User>    

                {    

                        new User(){ Name = "webabcd01", DayOfBirth = new DateTime(1980, 1, 1) }, 

                        new User(){ Name = "webabcd02", DayOfBirth = new DateTime(1980, 2, 2) }, 

                        new User(){ Name = "webabcd03", DayOfBirth = new DateTime(1980, 3, 3) }, 

                }; 

Xml.xaml

<UserControl x:Class="Silverlight20.Communication.Xml" 

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

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

        <StackPanel HorizontalAlignment="Left" Width="600"> 

                <TextBox x:Name="txtMsgXml" Margin="5" /> 

                <TextBox x:Name="txtMsgXml2" Margin="5" /> 

        </StackPanel> 

</UserControl>

Xml.xaml.cs

using System.Net; 

using System.Windows; 

using System.Windows.Controls; 

using System.Windows.Documents; 

using System.Windows.Input; 

using System.Windows.Media; 

using System.Windows.Media.Animation; 

using System.Windows.Shapes; 

using System.Xml.Linq; 

namespace Silverlight20.Communication 

        public partial class Xml : UserControl 

                public Xml() 

                { 

                        InitializeComponent(); 

                        // 演示如何处理 XML(对象) 

                        XmlDemo(); 

                        // 演示如何处理 XML(集合) 

                        XmlDemo2(); 

                } 

                /// <summary> 

                /// 演示如何处理 XML(对象) 

                /// </summary> 

                void XmlDemo() 

                        // REST 服务的 URL 

                        Uri uri = new Uri("http://localhost:3036/REST.svc/User/webabcd/xml", UriKind.Absolute); 

                        // 实例化 WebClient 

                        System.Net.WebClient client = new System.Net.WebClient(); 

                        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xml_DownloadStringCompleted); 

                        client.DownloadStringAsync(uri); 

                        txtMsgXml.Text = "读取 XML(对象) 数据中。。。"; 

                void xml_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 

                        if (e.Error != null) 

                        { 

                                // 发生错误的话,则打印出来 

                                txtMsgXml.Text = e.Error.ToString(); 

                                return; 

                        } 

                        // 将获得的字符串转换为 XML(对象) 

                        var buffer = System.Text.Encoding.UTF8.GetBytes(e.Result); 

                        var ms = new MemoryStream(buffer); 

                        XElement xmlObject = XElement.Load(ms); 

                        txtMsgXml.Text = e.Result + "\r\n"; 

                        XNamespace ns = "http://webabcd.cnblogs.com/"; 

                        txtMsgXml.Text += string.Format("姓名: {0}, 生日: {1}", 

                                (string)xmlObject.Element(ns + "Name"), 

                                ((DateTime)xmlObject.Element(ns + "DayOfBirth")).ToString("yyyy-MM-dd")); 

                        /*    

                         * 总结: 

                         * XElement - 表示一个 XML 元素 

                         *         XElement.Element - XML 元素内的 XML 元素 

                         *         XElement.Attribute - XML 元素内的 XML 属性 

                         *         XElement.Load(Stream) - 使用指定流创建一个 XElement 对象 

                         *         XElement.Parse(String) - 解析指定的 XML 字符串为一个 XElement 对象 

                         * XAttribute - 表示一个 XML 属性 

                         */ 

                /// 演示如何处理 XML(集合) 

                void XmlDemo2() 

                        Uri uri = new Uri("http://localhost:3036/REST.svc/Users/xml", UriKind.Absolute); 

                        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xml2_DownloadStringCompleted); 

                        txtMsgXml2.Text = "读取 XML(集合) 数据中。。。"; 

                void xml2_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 

                                txtMsgXml2.Text = e.Error.ToString(); 

                        // 将获得的字符串转换为 XML(集合) 

                        XDocument xmlObject = XDocument.Parse(e.Result); 

                        txtMsgXml2.Text = e.Result + "\r\n"; 

                        var obj = from p in xmlObject.Elements(ns + "ArrayOfUser").Elements(ns + "User") 

                                            where p.Element(ns + "Name").Value == "webabcd02" 

                                            select new { Name = (string)p.Element(ns + "Name"), DayOfBirth = (DateTime)p.Element(ns + "DayOfBirth") }; 

                        txtMsgXml2.Text += string.Format("姓名: {0}, 生日: {1}", 

                                obj.First().Name, 

                                obj.First().DayOfBirth.ToString("yyyy-MM-dd")); 

                         * LINQ to XML 相当的方便 

}

3、调用 REST 服务,返回 Rss/Atom 数据

Proxy.aspx.cs(返回指定的url地址的内容的服务)

using System.Web; 

using System.Web.UI; 

using System.Web.UI.WebControls; 

public partial class Proxy : System.Web.UI.Page 

        protected void Page_Load(object sender, EventArgs e) 

                // 获取某个 url 地址的 html 并在页面上输出 

                string url = Request.QueryString["url"]; 

                System.Net.WebClient client = new System.Net.WebClient(); 

                client.Encoding = System.Text.Encoding.UTF8; 

                Response.Write(client.DownloadString(url)); 

                Response.End(); 

RssAtom.xaml

<UserControl x:Class="Silverlight20.Communication.RssAtom" 

        <StackPanel HorizontalAlignment="Left" > 

                <TextBox x:Name="txtMsgRss" Width="600" Margin="5" /> 

                <StackPanel Orientation="Horizontal"> 

                        <ListBox x:Name="list" Width="300" Margin="5" SelectionChanged="list_SelectionChanged"> 

                                <ListBox.ItemTemplate> 

                                        <DataTemplate> 

                                                <TextBlock Text="{Binding Title.Text}"></TextBlock> 

                                        </DataTemplate> 

                                </ListBox.ItemTemplate> 

                        </ListBox> 

                        <TextBlock x:Name="detail" Width="300" Margin="5" Text="{Binding Summary.Text}" TextWrapping="Wrap" /> 

                </StackPanel> 

RssAtom.xaml.cs

using System.Xml; 

using System.ServiceModel.Syndication; 

        public partial class RssAtom : UserControl 

                public RssAtom() 

                        // 演示如何处理 Rss/Atom 

                        RssDemo(); 

                /// 演示如何处理 Rss/Atom 

                void RssDemo() 

                        // 让一个代理页面去请求相关的 Rss/Atom(如果用Silverlight直接去请求,则需要在目标域的根目录下配置策略文件) 

                        Uri uri = new Uri("http://localhost:3036/Proxy.aspx?url=http://webabcd.cnblogs.com/rss", UriKind.Absolute); 

                        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(rss_DownloadStringCompleted); 

                        txtMsgRss.Text = "读取 RSS 数据中。。。"; 

                void rss_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 

                                txtMsgRss.Text = e.Error.ToString(); 

                        // 将获得的字符串转换为 XmlReader 

                        XmlReader reader = XmlReader.Create(ms); 

                        // 从指定的 XmlReader 中加载,以生成 SyndicationFeed 

                        SyndicationFeed feed = SyndicationFeed.Load(reader); 

                        // 设置 list 的数据源为 Rss/Atom 的项集合(SyndicationFeed.Items) 

                        list.ItemsSource = feed.Items; 

                        txtMsgRss.Text = e.Result + "\r\n"; 

                private void list_SelectionChanged(object sender, SelectionChangedEventArgs e) 

                        // 设置 detail 的数据上下文为 Rss/Atom 的指定项(SyndicationItem) 

                        detail.DataContext = list.SelectedItem as SyndicationItem; 

OK

<a href="http://down.51cto.com/data/100302" target="_blank">[源码下载]</a>

     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/343113,如需转载请自行联系原作者