序列化
string xmlStr = ""; var dto = new ReqDto() { ErrorCode = 200, ReqName = "test" }; XmlSerializer serializer = new XmlSerializer(typeof(ReqDto)); using (StringWriter textWriter = new StringWriter()) { serializer.Serialize(textWriter, dto); xmlStr = textWriter.ToString(); }
序列化2
Person[] ps = new Person[3]; ps[0] = p; ps[1] = p; ps[2] = p; //使用XML序列化对象 string fileName = @"D:\users\lizw\桌面\Programmers.xml";//文件名称与路径 Stream fStream = new FileStream(fileName, FileMode.Create); XmlSerializer xmlFormat = new XmlSerializer(typeof(Person[])); xmlFormat.Serialize(fStream, ps);//序列化对象 fStream.Dispose();//关闭文件
反序列化
var len = Convert.ToInt32(HttpContext.Request.ContentLength); byte[] byt = new byte[len]; var ri = HttpContext.Request.BodyReader.AsStream().Read(byt, 0, len); string str = Encoding.UTF8.GetString(byt, 0, len); //如果传的是xml字符串,反序列化成对象。 ReqDto? dto = null; XmlSerializer serializer = new XmlSerializer(typeof(ReqDto)); using (StringReader sr = new StringReader(str)) { object? obj = serializer.Deserialize(sr); if (obj != null) { dto = (ReqDto)obj; } }
标签:xml,ps,ReqDto,new,net,序列化,XmlSerializer From: https://www.cnblogs.com/xsj1989/p/18121210