dynamic解析Http xml格式响应数据

来源:互联网 发布:java 高性能框架 编辑:程序博客网 时间:2024/05/22 04:29

继续上一篇 构建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, 0, 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 = 0;                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}", "600000"));            this.txtGetUrl.Text = client.BaseUri + String.Format("user/search/{0}", "600000");            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>","90000","post请求",1000,"好基友");            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;        }

测试结果:

 

噢了。。。

 

 


<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击