在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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>
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论