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

简介:
2、调用 REST 服务,返回 XML 数据
REST.cs(WCF创建的REST服务)
InBlock.gif using System; 
InBlock.gif using System.Linq; 
InBlock.gif using System.Runtime.Serialization; 
InBlock.gif using System.ServiceModel; 
InBlock.gif using System.ServiceModel.Activation; 
InBlock.gif 
InBlock.gif using System.ServiceModel.Web; 
InBlock.gif using System.Collections.Generic; 
InBlock.gif using System.Text; 
InBlock.gif using System.IO; 
InBlock.gif 
/// <summary> 
/// 提供 REST 服务的类 
/// 注:Silverlight只支持 GET 和 POST 
/// </summary> 
InBlock.gif[ServiceContract] 
InBlock.gif[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
InBlock.gif public  class REST 
InBlock.gif
InBlock.gif         /// <summary> 
InBlock.gif         /// 用于演示返回 XML(对象) 的 REST 服务 
InBlock.gif         /// </summary> 
InBlock.gif         /// <param name="name"></param> 
InBlock.gif         /// <returns></returns> 
InBlock.gif        [OperationContract] 
InBlock.gif        [WebGet(UriTemplate =  "User/{name}/xml", ResponseFormat = WebMessageFormat.Xml)] 
InBlock.gif         public User HelloXml( string name) 
InBlock.gif        { 
InBlock.gif                 return  new User { Name = name, DayOfBirth =  new DateTime(1980, 2, 14) }; 
InBlock.gif        } 
InBlock.gif 
InBlock.gif         /// <summary> 
InBlock.gif         /// 用于演示返回 XML(集合) 的 REST 服务 
InBlock.gif         /// </summary> 
InBlock.gif         /// <returns></returns> 
InBlock.gif        [OperationContract] 
InBlock.gif        [WebGet(UriTemplate =  "Users/xml", ResponseFormat = WebMessageFormat.Xml)] 
InBlock.gif         public List<User> HelloXml2() 
InBlock.gif        { 
InBlock.gif                 return  new List<User>    
InBlock.gif                {    
InBlock.gif                         new User(){ Name =  "webabcd01", DayOfBirth =  new DateTime(1980, 1, 1) }, 
InBlock.gif                         new User(){ Name =  "webabcd02", DayOfBirth =  new DateTime(1980, 2, 2) }, 
InBlock.gif                         new User(){ Name =  "webabcd03", DayOfBirth =  new DateTime(1980, 3, 3) }, 
InBlock.gif                }; 
InBlock.gif        } 
InBlock.gif
 
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
InBlock.gif using System; 
InBlock.gif using System.Collections.Generic; 
InBlock.gif using System.Linq; 
InBlock.gif using System.Net; 
InBlock.gif using System.Windows; 
InBlock.gif using System.Windows.Controls; 
InBlock.gif using System.Windows.Documents; 
InBlock.gif using System.Windows.Input; 
InBlock.gif using System.Windows.Media; 
InBlock.gif using System.Windows.Media.Animation; 
InBlock.gif using System.Windows.Shapes; 
InBlock.gif 
InBlock.gif using System.Xml.Linq; 
InBlock.gif using System.IO; 
InBlock.gif 
InBlock.gif namespace Silverlight20.Communication 
InBlock.gif
InBlock.gif         public partial  class Xml : UserControl 
InBlock.gif        { 
InBlock.gif                 public Xml() 
InBlock.gif                { 
InBlock.gif                        InitializeComponent(); 
InBlock.gif 
InBlock.gif                         // 演示如何处理 XML(对象) 
InBlock.gif                        XmlDemo(); 
InBlock.gif 
InBlock.gif                         // 演示如何处理 XML(集合) 
InBlock.gif                        XmlDemo2(); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 /// <summary> 
InBlock.gif                 /// 演示如何处理 XML(对象) 
InBlock.gif                 /// </summary> 
InBlock.gif                 void XmlDemo() 
InBlock.gif                { 
InBlock.gif                         // REST 服务的 URL 
InBlock.gif                        Uri uri =  new Uri( "http://localhost:3036/REST.svc/User/webabcd/xml", UriKind.Absolute); 
InBlock.gif 
InBlock.gif                        // 实例化 WebClient 
InBlock.gif                        System.Net.WebClient client = new System.Net.WebClient(); 
InBlock.gif 
InBlock.gif                        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xml_DownloadStringCompleted); 
InBlock.gif                        client.DownloadStringAsync(uri); 
InBlock.gif 
InBlock.gif                        txtMsgXml.Text = "读取 XML(对象) 数据中。。。"
InBlock.gif                } 
InBlock.gif 
InBlock.gif                void xml_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
InBlock.gif                { 
InBlock.gif                        if (e.Error != null
InBlock.gif                        { 
InBlock.gif                                // 发生错误的话,则打印出来 
InBlock.gif                                txtMsgXml.Text = e.Error.ToString(); 
InBlock.gif                                return
InBlock.gif                        } 
InBlock.gif 
InBlock.gif                        // 将获得的字符串转换为 XML(对象) 
InBlock.gif                        var buffer = System.Text.Encoding.UTF8.GetBytes(e.Result); 
InBlock.gif                        var ms = new MemoryStream(buffer); 
InBlock.gif 
InBlock.gif                        XElement xmlObject = XElement.Load(ms); 
InBlock.gif 
InBlock.gif                        txtMsgXml.Text = e.Result + "\r\n"
InBlock.gif                        XNamespace ns = "http://webabcd.cnblogs.com/"; 
InBlock.gif                        txtMsgXml.Text += string.Format("姓名: {0}, 生日: {1}"
InBlock.gif                                (string)xmlObject.Element(ns + "Name"), 
InBlock.gif                                ((DateTime)xmlObject.Element(ns + "DayOfBirth")).ToString("yyyy-MM-dd")); 
InBlock.gif 
InBlock.gif                        /*    
InBlock.gif                         * 总结: 
InBlock.gif                         * XElement - 表示一个 XML 元素 
InBlock.gif                         *         XElement.Element - XML 元素内的 XML 元素 
InBlock.gif                         *         XElement.Attribute - XML 元素内的 XML 属性 
InBlock.gif                         *         XElement.Load(Stream) - 使用指定流创建一个 XElement 对象 
InBlock.gif                         *         XElement.Parse(String) - 解析指定的 XML 字符串为一个 XElement 对象 
InBlock.gif                         * XAttribute - 表示一个 XML 属性 
InBlock.gif                         */
 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                /// <summary> 
InBlock.gif                /// 演示如何处理 XML(集合) 
InBlock.gif                /// </summary> 
InBlock.gif                void XmlDemo2() 
InBlock.gif                { 
InBlock.gif                        // REST 服务的 URL 
InBlock.gif                        Uri uri = new Uri("http://localhost:3036/REST.svc/Users/xml", UriKind.Absolute); 
InBlock.gif 
InBlock.gif                        // 实例化 WebClient 
InBlock.gif                        System.Net.WebClient client = new System.Net.WebClient(); 
InBlock.gif 
InBlock.gif                        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xml2_DownloadStringCompleted); 
InBlock.gif                        client.DownloadStringAsync(uri); 
InBlock.gif 
InBlock.gif                        txtMsgXml2.Text = "读取 XML(集合) 数据中。。。"
InBlock.gif                } 
InBlock.gif 
InBlock.gif                void xml2_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
InBlock.gif                { 
InBlock.gif                        if (e.Error != null
InBlock.gif                        { 
InBlock.gif                                // 发生错误的话,则打印出来 
InBlock.gif                                txtMsgXml2.Text = e.Error.ToString(); 
InBlock.gif                                return
InBlock.gif                        } 
InBlock.gif 
InBlock.gif                        // 将获得的字符串转换为 XML(集合) 
InBlock.gif                        XDocument xmlObject = XDocument.Parse(e.Result); 
InBlock.gif 
InBlock.gif                        txtMsgXml2.Text = e.Result + "\r\n"
InBlock.gif                        XNamespace ns = "http://webabcd.cnblogs.com/"; 
InBlock.gif                        var obj = from p in xmlObject.Elements(ns + "ArrayOfUser").Elements(ns + "User"
InBlock.gif                                            where p.Element(ns + "Name").Value == "webabcd02" 
InBlock.gif                                            select new { Name = (string)p.Element(ns + "Name"), DayOfBirth = (DateTime)p.Element(ns + "DayOfBirth") }; 
InBlock.gif                         
InBlock.gif                        txtMsgXml2.Text += string.Format("姓名: {0}, 生日: {1}"
InBlock.gif                                obj.First().Name, 
InBlock.gif                                obj.First().DayOfBirth.ToString("yyyy-MM-dd")); 
InBlock.gif 
InBlock.gif 
InBlock.gif                        /*    
InBlock.gif                         * 总结: 
InBlock.gif                         * LINQ to XML 相当的方便 
InBlock.gif                         */
 
InBlock.gif                } 
InBlock.gif        } 
InBlock.gif}
 
 
3、调用 REST 服务,返回 Rss/Atom 数据
Proxy.aspx.cs(返回指定的url地址的内容的服务)
InBlock.gif using System; 
InBlock.gif using System.Collections.Generic; 
InBlock.gif using System.Linq; 
InBlock.gif using System.Web; 
InBlock.gif using System.Web.UI; 
InBlock.gif using System.Web.UI.WebControls; 
InBlock.gif 
InBlock.gif public partial  class Proxy : System.Web.UI.Page 
InBlock.gif
InBlock.gif         protected  void Page_Load( object sender, EventArgs e) 
InBlock.gif        { 
InBlock.gif                 // 获取某个 url 地址的 html 并在页面上输出 
InBlock.gif 
InBlock.gif                 string url = Request.QueryString[ "url"]; 
InBlock.gif 
InBlock.gif                System.Net.WebClient client =  new System.Net.WebClient(); 
InBlock.gif                client.Encoding = System.Text.Encoding.UTF8; 
InBlock.gif 
InBlock.gif                Response.Write(client.DownloadString(url)); 
InBlock.gif                Response.End(); 
InBlock.gif        } 
InBlock.gif}
 
RssAtom.xaml
<UserControl x:Class="Silverlight20.Communication.RssAtom" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
        <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> 
                 
        </StackPanel> 
</UserControl>
 
RssAtom.xaml.cs
InBlock.gif using System; 
InBlock.gif using System.Collections.Generic; 
InBlock.gif using System.Linq; 
InBlock.gif using System.Net; 
InBlock.gif using System.Windows; 
InBlock.gif using System.Windows.Controls; 
InBlock.gif using System.Windows.Documents; 
InBlock.gif using System.Windows.Input; 
InBlock.gif using System.Windows.Media; 
InBlock.gif using System.Windows.Media.Animation; 
InBlock.gif using System.Windows.Shapes; 
InBlock.gif 
InBlock.gif using System.Xml; 
InBlock.gif using System.IO; 
InBlock.gif using System.ServiceModel.Syndication; 
InBlock.gif 
InBlock.gif namespace Silverlight20.Communication 
InBlock.gif
InBlock.gif         public partial  class RssAtom : UserControl 
InBlock.gif        { 
InBlock.gif                 public RssAtom() 
InBlock.gif                { 
InBlock.gif                        InitializeComponent(); 
InBlock.gif 
InBlock.gif                         // 演示如何处理 Rss/Atom 
InBlock.gif                        RssDemo(); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 /// <summary> 
InBlock.gif                 /// 演示如何处理 Rss/Atom 
InBlock.gif                 /// </summary> 
InBlock.gif                 void RssDemo() 
InBlock.gif                { 
InBlock.gif                         // 让一个代理页面去请求相关的 Rss/Atom(如果用Silverlight直接去请求,则需要在目标域的根目录下配置策略文件) 
InBlock.gif                        Uri uri =  new Uri( "http://localhost:3036/Proxy.aspx?url=http://webabcd.cnblogs.com/rss", UriKind.Absolute); 
InBlock.gif 
InBlock.gif                        // 实例化 WebClient 
InBlock.gif                        System.Net.WebClient client = new System.Net.WebClient(); 
InBlock.gif 
InBlock.gif                        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(rss_DownloadStringCompleted); 
InBlock.gif                        client.DownloadStringAsync(uri); 
InBlock.gif 
InBlock.gif                        txtMsgRss.Text = "读取 RSS 数据中。。。"
InBlock.gif                } 
InBlock.gif 
InBlock.gif                void rss_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
InBlock.gif                { 
InBlock.gif                        if (e.Error != null
InBlock.gif                        { 
InBlock.gif                                // 发生错误的话,则打印出来 
InBlock.gif                                txtMsgRss.Text = e.Error.ToString(); 
InBlock.gif                                return
InBlock.gif                        } 
InBlock.gif 
InBlock.gif                        // 将获得的字符串转换为 XmlReader 
InBlock.gif                        var buffer = System.Text.Encoding.UTF8.GetBytes(e.Result); 
InBlock.gif                        var ms = new MemoryStream(buffer); 
InBlock.gif                        XmlReader reader = XmlReader.Create(ms); 
InBlock.gif 
InBlock.gif                        // 从指定的 XmlReader 中加载,以生成 SyndicationFeed 
InBlock.gif                        SyndicationFeed feed = SyndicationFeed.Load(reader); 
InBlock.gif 
InBlock.gif                        // 设置 list 的数据源为 Rss/Atom 的项集合(SyndicationFeed.Items) 
InBlock.gif                        list.ItemsSource = feed.Items; 
InBlock.gif                        txtMsgRss.Text = e.Result + "\r\n"
InBlock.gif                } 
InBlock.gif 
InBlock.gif                private void list_SelectionChanged(object sender, SelectionChangedEventArgs e) 
InBlock.gif                { 
InBlock.gif                        // 设置 detail 的数据上下文为 Rss/Atom 的指定项(SyndicationItem) 
InBlock.gif                        detail.DataContext = list.SelectedItem as SyndicationItem; 
InBlock.gif                } 
InBlock.gif        } 
InBlock.gif}
 




     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/343113 ,如需转载请自行联系原作者
相关文章
|
2月前
|
XML 前端开发 数据格式
请描述如何使用`BeautifulSoup`或其他类似的库来解析 HTML 或 XML 数据。
【2月更文挑战第22天】【2月更文挑战第67篇】请描述如何使用`BeautifulSoup`或其他类似的库来解析 HTML 或 XML 数据。
|
4月前
|
XML 存储 JSON
Python学习 -- 常用数据交换格式(CSV、XML、JSON)
Python学习 -- 常用数据交换格式(CSV、XML、JSON)
31 0
|
3月前
|
XML 机器学习/深度学习 JSON
在火狐浏览器调ajax获取json数据时,控制台提示“XML 解析错误:格式不佳”。
在火狐浏览器调ajax获取json数据时,控制台提示“XML 解析错误:格式不佳”。
31 0
在火狐浏览器调ajax获取json数据时,控制台提示“XML 解析错误:格式不佳”。
|
1天前
|
XML 前端开发 数据格式
BeautifulSoup 是一个 Python 库,用于从 HTML 和 XML 文件中提取数据
BeautifulSoup 是 Python 的一个库,用于解析 HTML 和 XML 文件,即使在格式不规范的情况下也能有效工作。通过创建 BeautifulSoup 对象并使用方法如 find_all 和 get,可以方便地提取和查找文档中的信息。以下是一段示例代码,展示如何安装库、解析 HTML 数据以及打印段落、链接和特定类名的元素。BeautifulSoup 还支持更复杂的查询和文档修改功能。
6 1
|
2天前
|
XML 存储 JSON
c#XML、JSON的序列化和反序列化,看完你就懂了
c#XML、JSON的序列化和反序列化,看完你就懂了
6 0
|
12天前
|
XML JSON 前端开发
【Web 前端】XML和JSON的区别?
【4月更文挑战第22天】【Web 前端】XML和JSON的区别?
【Web 前端】XML和JSON的区别?
|
12天前
|
JSON 安全 API
【专栏】四种REST API身份验证方法:基本认证、OAuth、JSON Web Token(JWT)和API密钥
【4月更文挑战第28天】本文探讨了四种REST API身份验证方法:基本认证、OAuth、JSON Web Token(JWT)和API密钥。基本认证简单但不安全;OAuth适用于授权第三方应用;JWT提供安全的身份验证信息传递;API密钥适合内部使用。选择方法时需平衡安全性、用户体验和开发复杂性。
|
15天前
|
XML JSON 中间件
中间件数据格式JSON与XML之间的转换
中间件数据格式JSON与XML之间的转换
28 3
|
1月前
|
XML JSON JavaScript
Java中XML和JSON的比较与应用指南
本文对比了Java中XML和JSON的使用,XML以自我描述性和可扩展性著称,适合结构复杂、需验证的场景,但语法冗长。JSON结构简洁,适用于轻量级数据交换,但不支持命名空间。在Java中,处理XML可使用DOM、SAX解析器或XPath,而JSON可借助GSON、Jackson库。根据需求选择合适格式,注意安全、性能和可读性。
28 0
|
1月前
|
XML JSON 安全
xml与json的区别
xml与json的区别
10 0