dynamic解析Http xml格式响应数据
继续上一篇 构建RESTful风格的WCF服务 ,咱已经把服务端的数据和服务准备好了,客户端调用 wcf rest接口后如何解析xml?下面使用dynamic关键字解析来至于WCF REST XML响应数据。
首先创建一个WCF客户端类,添加GET、POST处理方法:
public class WcfRestClient
{
public Uri BaseUri { get; private set; } //Url:http://localhost:1008/ public WcfRestClient(Uri baseUri)
{
BaseUri = baseUri;
} public WcfRestClient(string baseUrl)
: this(new Uri(baseUrl))
{ } private dynamic GetResponseObject(HttpWebRequest request)
{
try
{
var response = request.GetResponse() as HttpWebResponse;
using (var stream = response.GetResponseStream())
{
if (!stream.CanRead)
return null;
StreamReader reader = new StreamReader(stream);
string source = reader.ReadToEnd();
response.Close();
return XmlStringToDynamic(source);
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
{
if (!stream.CanRead)
return null;
StreamReader reader = new StreamReader(stream);
string source = reader.ReadToEnd();
return XmlStringToDynamic(source);
}
}
}
//GET请求
public dynamic WebGet(string path)
{
HttpWebRequest request=(HttpWebRequest)HttpWebRequest.Create(BaseUri.ToString()+path);
return GetResponseObject(request);
}
//POST请求
public dynamic WebPost(string path, string data)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(BaseUri.ToString() + path);
request.Method = "POST";
if (!String.IsNullOrEmpty(data))
{
request.ContentType = "text/xml"; //xml格式传输数据
byte[] buffer = Encoding.UTF8.GetBytes(data);
request.ContentLength = buffer.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(buffer, , buffer.Length);
stream.Flush();
}
}
return GetResponseObject(request);
}
//
public static dynamic XmlStringToDynamic(string xml)
{
if (String.IsNullOrEmpty(xml))
return null;
XElement element = XElement.Parse(xml);
dynamic dynamicResult = new DynamicXMLNode(element);
return dynamicResult;
}
}
2、dynamic处理xml节点DynamicXMLNode类,需要继承DynamicObject(System.Dynamic),对返回的xml对象进行动态解析。
public class DynamicXMLNode:DynamicObject
{
public DynamicXMLNode() { } XElement node; public XElement Element
{
get
{
return node;
}
} public DynamicXMLNode(XElement node)
{
this.node = node;
} public DynamicXMLNode(string name)
{
node = new XElement(name);
} public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (binder.Name == "Value")
{
result = node.Value;
return true;
}
if (binder.Name == "ElementCount")
{
if (node.HasElements)
result = node.Elements().Count();
else
result = ;
return true;
}
XElement getNode;
try
{
getNode = node.Element(binder.Name);
}
catch
{
result = null;
return true;
}
if (getNode != null)
{
result = new DynamicXMLNode(getNode);
return true;
}
else
{
result = null;
return false;
}
} }
3、最后咱们来测试一下发起GET和POST请求,首先创建一个aspx页面,在.cs文件:
/// <summary>
/// 处理GET请求
/// </summary>
private void GetData()
{
WcfRestClient client = new WcfRestClient("http://localhost:1008/");
dynamic result = client.WebGet(String.Format("user/search/{0}", ""));
this.txtGetUrl.Text = client.BaseUri + String.Format("user/search/{0}", "");
this.txtId.Text = result.Id.Value;
this.txtCode.Text = result.Code.Value;
this.txtName.Text = result.Name.Value;
this.txtDesc.Text = result.Description.Value;
} /// <summary>
/// 测试POST请求
/// </summary>
private void PostData()
{
string strBuiler = String.Format("<UserInfo><Code>{0}</Code><Description>{1}</Description><Id>{2}</Id><Name>{3}</Name></UserInfo>","","post请求",,"好基友");
WcfRestClient client = new WcfRestClient("http://localhost:1008/");
dynamic result = client.WebPost("user/register", strBuiler);
this.txtPOSTUrl.Text = client.BaseUri + "user/register";
this.txtId1.Text = result.Id.Value;
this.txtCode1.Text = result.Code.Value;
this.txtName1.Text = result.Name.Value;
this.txtDesc1.Text = result.Description.Value;
}
测试结果:

噢了。。。
dynamic解析Http xml格式响应数据的更多相关文章
- scrapy 解析xml格式的数据
XMLFeedSpider 主要用于 解析 xml格式的数据 创建一个scrapy 项目文件 scrapy startproject xxx 创建一个spider scrapy genspider - ...
- 如何在JSP页面里面显示xml格式的数据
正常情况下,在jsp页面里的标签里写xml格式的数据,在浏览器里面的页面里显示出来的是乱码. 为什么会显示乱码呢?原来xml标签在jsp里会被解析为浏览器对象,因为xml最开始被设计出来是 为了写网页 ...
- xml格式的数据转化成数组
将得到的xml格式的数据转化成数组 <?php //构造xml $url = "http://api.map.baidu.com/telematics/v3/weather?locat ...
- C#操作数据表中XML格式的数据
以前还真没有见过数据表中存储XML格式的数据,刚开始听说的时候,还以为是数据表中有XML的字段类型, 再了解,其实也就是字符串类型的,只不过字符串的格式是XML格式的.确实孤陋寡闻!汗... (可添加 ...
- SpringMVC处理XML格式的数据
1.搭建SpringMVC+spring环境 2.web.xml,Springmvc-config.xml.springMVC提供了处理xml格式请求响应的HttpMessageConverter,s ...
- Asp.net Core WebApi 支持json/xml格式的数据返回
Asp.net core 在做webapi项目的时候,默认是只返回json格式的数据的,如果想要开启xml数据返回,需要在startup里配置如下: public void ConfigureServ ...
- android开发 服务器端访问MySQL数据库,并把数据库中的某张表解析成xml格式输出到浏览器
我们此时只要写一个Servlet就可以了: public class UpdateMenuServlet extends HttpServlet { /** * */ private static f ...
- 关于java后台如何接收xml格式的数据
业务场景:用户发送下单请求,格式为xml格式,服务器接收数据完成下单,并返回结果给客户. 请求格式: <request> <head> <sign></sig ...
- JAVA 读取xml格式的数据
<?xml version="1.0" encoding="UTF-8"?> <column-enums> <type name= ...
随机推荐
- Spark应用程序的运行架构几种说
(1)简单的说: 由driver向集群申请资源,集群分配资源,启动executor.driver将spark应用程序的代码和文件传送给executor.executor上运行task,运行完之后将结果 ...
- spring aop方式配置事务中的三个概念 pointcut advice advisor
AOP的3个关键概念 因为AOP的概念难于理解,所以在前面首先对Java动态代理机制进行了一下讲解,从而使读者能够循序渐进地来理解AOP的思想. 学习AOP,关键在于理解AOP的思想,能够使用AOP. ...
- mySQl数据库中不能插入中文的处理办法
1. 修改MySQL安装目录下(C:\Program Files\MySQL\MySQL Server 5.5)的my.ini文件 设置: default-character-set=utf8 cha ...
- Delphi Dll 动态调用例子(1)
http://blog.sina.com.cn/s/blog_62c46c3701010q7h.html 一.编写dll library TestDllByD2007; uses SysUtils, ...
- asp.net mvc 在JS中跳转到其它controller/action
平时在ASP.NET 中经常这样写, $('#loginOut').click(function() { $.messager.confirm('系统提示', '您确定要退出本次登 ...
- [翻译]NUnit---TearDown and SetUpFixture and Test Attributes(二十)
TearDownAttribute (NUnit 2.0 / 2.5) 本特性在TestFixture内部使用,每个测试方法执行后调用的方法集.也可以在SetUpFixture中使用,在同一命名空间或 ...
- jenkins常用插件汇总
jenkins常用插件汇总: Build-timeout Plugin:任务构建超时插件 Naginator Plugin:任务重试插件 Build User Vars Plugin:用户变量获取插件 ...
- ASP.NET Core使用EF Core操作MySql数据库
ASP.NET Core操作MySql数据库, 这样整套环境都可以布署在Linux上 使用微软的 Microsoft.EntityFrameworkCore(2.1.4) 和MySql出的 MySql ...
- App.config使用方法(基础教程)
WPF程序中的App.config文件是应用程序中经常使用的一种配置文件,System.Configuration.dll文件中提供了大量的读写的配置,是一种很高效的程序配置方式. 1.首先在工程中配 ...
- 3D Spherical Geometry Kernel( Geometry Kernels) CGAL 4.13 -User Manual
Introduction The goal of the 3D spherical kernel is to offer to the user a large set of functionalit ...