标签:col mes ati buffer uil 去除 序列 nbsp factory
1 #region 序列化 2 public static string Serializer<T>(T t) 3 { 4 //StringBuilder sb = new StringBuilder(); 5 using (MemoryStream ms = new MemoryStream()) 6 { 7 using (System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8)) 8 { 9 XmlSerializerFactory xmlSerializerFactory = new XmlSerializerFactory(); 10 string name = t.GetType().Name; 11 12 XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); 13 //Add an empty namespace and empty value 14 ns.Add("", ""); 15 16 XmlSerializer xmlSerializer = xmlSerializerFactory.CreateSerializer(typeof(T)); 17 18 xmlSerializer.Serialize(xw, t); 19 20 // 去除BOM 21 byte[] buffer = ms.ToArray(); 22 23 if (buffer.Length <= 3) 24 { 25 return Encoding.UTF8.GetString(buffer); 26 } 27 byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf }; 28 if (buffer[0] == bomBuffer[0] && buffer[1] == bomBuffer[1] && buffer[2] == bomBuffer[2]) 29 { 30 return Encoding.UTF8.GetString(buffer, 3, buffer.Length - 3); 31 } 32 return Encoding.UTF8.GetString(buffer); 33 } 34 } 35 } 36 #endregion 37 38 #region 反序列化 39 public static T Deserialize<T>(string xml) 40 { 41 using (StringReader reader = new StringReader(xml)) 42 { 43 XmlSerializer xs = new XmlSerializer(typeof(T)); 44 T obj = (T)xs.Deserialize(reader); 45 return obj; 46 } 47 } 48 #endregion
标签:col mes ati buffer uil 去除 序列 nbsp factory
原文地址:https://www.cnblogs.com/hugeboke/p/11575208.html