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>

  

posted @ 2016-01-24 21:32  shuanzhi  阅读(4470)  评论(0编辑  收藏  举报