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, 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"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值