C#的XML序列化及反序列化

  webservice在工作中用到的很多,基本都是以XML格式问通讯内容,其中最关键的就是XML串的序列化及反序列化。

  XML的运用中有两种信息传递,一种为XML的请求信息,另一种为返回信息,要运用XML,首先要为这两种返回信息新建实体类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace Test1
{
    [Serializable]
    public class RequestBase
    {
        [XmlElement(Order = 1)]
        public string Name
        {
            get;
            set;
        }

        [XmlElement(Order = 2)]
        public string Age
        {
            get;
            set;
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace Test1
{
    [Serializable]
    public class ResponseBase
    {
        [XmlElement(Order = 1)]
        public string Information
        {
            get;
            set;
        }
    }
}

  然后编写将XML序列化和反序列化的方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
using System.IO;

namespace Test1
{
    public class Function
    {
        //反序列化
        public static T Deserialize<T>(string xml)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            StringReader sr = new StringReader(xml);
            T obj = (T)xs.Deserialize(sr);
            sr.Close();
            sr.Dispose();
            return obj;
        }

        //序列化
        public static string Serializer<T>(T t)
        {
            XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
            xsn.Add(string.Empty, string.Empty);
            XmlSerializer xs = new XmlSerializer(typeof(T));
            StringWriter sw=new StringWriter();
            xs.Serialize(sw, t, xsn);
            string str = sw.ToString();
            sw.Close();
            sw.Dispose();
            return str;
        }
    }
}

  然后再具体实现将请求信息通过代码处理变成返回信息的方法:

public string Test(string xml)
        {
            RequestBase request = Function.Deserialize<RequestBase>(xml);
            ResponseBase response = new ResponseBase();
            response.Information = "姓名:" + request.Name + " 年龄为:" + request.Age;
            return Function.Serializer<ResponseBase>(response);
        }

  示例XML:<?xml version="1.0" encoding="utf-8"?><RequestBase><Name>逗你玩</Name><Age>25</Age></RequestBase>

  返回值为:

<string xmlns="http://tempuri.org/">
<?xml version="1.0" encoding="utf-16"?> <ResponseBase> <Information>姓名:逗你玩 年龄为:25</Information> </ResponseBase>
</string>

  

转载于:https://www.cnblogs.com/yupeiyuan/p/5156023.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值