上接稳扎稳打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) }; 
        } 
 
         /// <summary> 
         /// 用于演示返回 XML(集合) 的 REST 服务 
         /// </summary> 
         /// <returns></returns> 
        [OperationContract] 
        [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; 
using System.Collections.Generic; 
using System.Linq; 
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; 
using System.IO; 
 
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 属性 
                         */
 
                } 
 
                /// <summary> 
                /// 演示如何处理 XML(集合) 
                /// </summary> 
                void XmlDemo2() 
                { 
                        // REST 服务的 URL 
                        Uri uri = new Uri("http://localhost:3036/REST.svc/Users/xml", UriKind.Absolute); 
 
                        // 实例化 WebClient 
                        System.Net.WebClient client = new System.Net.WebClient(); 
 
                        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xml2_DownloadStringCompleted); 
                        client.DownloadStringAsync(uri); 
 
                        txtMsgXml2.Text = "读取 XML(集合) 数据中。。。"
                } 
 
                void xml2_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
                { 
                        if (e.Error != null
                        { 
                                // 发生错误的话,则打印出来 
                                txtMsgXml2.Text = e.Error.ToString(); 
                                return
                        } 
 
                        // 将获得的字符串转换为 XML(集合) 
                        XDocument xmlObject = XDocument.Parse(e.Result); 
 
                        txtMsgXml2.Text = e.Result + "\r\n"
                        XNamespace ns = "http://webabcd.cnblogs.com/"; 
                        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; 
using System.Collections.Generic; 
using System.Linq; 
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" 
        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
using System; 
using System.Collections.Generic; 
using System.Linq; 
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; 
using System.IO; 
using System.ServiceModel.Syndication; 
 
namespace Silverlight20.Communication 

         public partial  class RssAtom : UserControl 
        { 
                 public RssAtom() 
                { 
                        InitializeComponent(); 
 
                         // 演示如何处理 Rss/Atom 
                        RssDemo(); 
                } 
 
                 /// <summary> 
                 /// 演示如何处理 Rss/Atom 
                 /// </summary> 
                 void RssDemo() 
                { 
                         // 让一个代理页面去请求相关的 Rss/Atom(如果用Silverlight直接去请求,则需要在目标域的根目录下配置策略文件) 
                        Uri uri =  new Uri( "http://localhost:3036/Proxy.aspx?url=http://webabcd.cnblogs.com/rss", UriKind.Absolute); 
 
                        // 实例化 WebClient 
                        System.Net.WebClient client = new System.Net.WebClient(); 
 
                        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(rss_DownloadStringCompleted); 
                        client.DownloadStringAsync(uri); 
 
                        txtMsgRss.Text = "读取 RSS 数据中。。。"
                } 
 
                void rss_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
                { 
                        if (e.Error != null
                        { 
                                // 发生错误的话,则打印出来 
                                txtMsgRss.Text = e.Error.ToString(); 
                                return
                        } 
 
                        // 将获得的字符串转换为 XmlReader 
                        var buffer = System.Text.Encoding.UTF8.GetBytes(e.Result); 
                        var ms = new MemoryStream(buffer); 
                        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; 
                } 
        } 
}
 




     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/343113 ,如需转载请自行联系原作者
相关文章
|
6月前
|
JSON API 数据格式
淘宝拍立淘按图搜索API系列,json数据返回
淘宝拍立淘按图搜索API系列通过图像识别技术实现商品搜索功能,调用后返回的JSON数据包含商品标题、图片链接、价格、销量、相似度评分等核心字段,支持分页和详细商品信息展示。以下是该API接口返回的JSON数据示例及详细解析:
|
6月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
6月前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
6月前
|
JSON Java Go
【GoGin】(2)数据解析和绑定:结构体分析,包括JSON解析、form解析、URL解析,区分绑定的Bind方法
bind或bindXXX函数(后文中我们统一都叫bind函数)的作用就是将,以方便后续业务逻辑的处理。
426 5
|
6月前
|
JSON 中间件 Java
【GoGin】(3)Gin的数据渲染和中间件的使用:数据渲染、返回JSON、浅.JSON()源码、中间件、Next()方法
我们在正常注册中间件时,会打断原有的运行流程,但是你可以在中间件函数内部添加Next()方法,这样可以让原有的运行流程继续执行,当原有的运行流程结束后再回来执行中间件内部的内容。​ c.Writer.WriteHeaderNow()还会写入文本流中。可以看到使用next后,正常执行流程中并没有获得到中间件设置的值。接口还提供了一个可以修改ContentType的方法。判断了传入的状态码是否符合正确的状态码,并返回。在内部封装时,只是标注了不同的render类型。再看一下其他返回的类型;
325 3
|
6月前
|
XML 数据采集 API
用Lxml高效解析XML格式数据:以天气API为例
免费Python教程:实战解析中国天气网XML数据,详解Lxml库高效解析技巧、XPath用法、流式处理大文件及IP封禁应对策略,助你构建稳定数据采集系统。
363 0
|
11月前
|
Android开发 开发者
Android自定义View之不得不知道的文件attrs.xml(自定义属性)
本文详细介绍了如何通过自定义 `attrs.xml` 文件实现 Android 自定义 View 的属性配置。以一个包含 TextView 和 ImageView 的 DemoView 为例,讲解了如何使用自定义属性动态改变文字内容和控制图片显示隐藏。同时,通过设置布尔值和点击事件,实现了图片状态的切换功能。代码中展示了如何在构造函数中解析自定义属性,并通过方法 `setSetting0n` 和 `setbackeguang` 实现功能逻辑的优化与封装。此示例帮助开发者更好地理解自定义 View 的开发流程与 attrs.xml 的实际应用。
321 2
Android自定义View之不得不知道的文件attrs.xml(自定义属性)
|
XML 前端开发 Java
讲解SSM的xml文件
本文详细介绍了SSM框架中的xml配置文件,包括springMVC.xml和applicationContext.xml,涉及组件扫描、数据源配置、事务管理、MyBatis集成以及Spring MVC的视图解析器配置。
350 1
|
XML Java 数据格式
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)
这篇文章是Spring5框架的实战教程,主要介绍了如何在Spring的IOC容器中通过XML配置方式使用外部属性文件来管理Bean,特别是数据库连接池的配置。文章详细讲解了创建属性文件、引入属性文件到Spring配置、以及如何使用属性占位符来引用属性文件中的值。
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)
|
Java Maven
maven项目的pom.xml文件常用标签使用介绍
第四届人文,智慧教育与服务管理国际学术会议(HWESM 2025) 2025 4th International Conference on Humanities, Wisdom Education and Service Management
1247 8
下一篇
开通oss服务