////// Xml序列化与反序列化 /// public class XmlUtil { public static string GetRoot(string xml) { if (xml == null) xml = "";//预防下边的 Replace()、Trim()报错 XmlDocument doc = new XmlDocument(); doc.LoadXml(xml.Replace("\r\n", "").Replace("\0", "").Trim()); var e = doc.DocumentElement; return e.InnerText; } #region 反序列化 ////// 反序列化 /// /// XML字符串 ///public static T Deserialize (string xml) { return (T)Deserialize(typeof(T), xml); } /// /// 反序列化 /// /// 字节流 ///public static T Deserialize (Stream stream) { return (T)Deserialize(typeof(T), stream); } /// /// 反序列化 /// /// 类型 /// XML字符串 ///public static object Deserialize(Type type, string xml) { if (xml == null) xml = "";//预防下边的 Replace()、Trim()报错 try { xml = xml.Replace("\r\n", "").Replace("\0", "").Trim(); using (StringReader sr = new StringReader(xml)) { XmlSerializer xmldes = new XmlSerializer(type); return xmldes.Deserialize(sr); } } catch (Exception e) { return null; } } /// /// 反序列化 /// /// /// ///public static object Deserialize(Type type, Stream stream) { XmlSerializer xmldes = new XmlSerializer(type); return xmldes.Deserialize(stream); } #endregion #region 序列化 /// /// 序列化 /// /// 对象 ///public static string Serializer (T obj) { return Serializer(typeof(T), obj); } /// /// 序列化 /// /// 类型 /// 对象 ///public static string Serializer(Type type, object obj) { MemoryStream Stream = new MemoryStream(); XmlSerializerNamespaces _name = new XmlSerializerNamespaces(); _name.Add("", "");//这样就 去掉 attribute 里面的 xmlns:xsi 和 xmlns:xsd XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Encoding = new UTF8Encoding(false);//设置编码,不能用Encoding.UTF8,会导致带有BOM标记 xmlWriterSettings.Indent = true;//设置自动缩进 //xmlWriterSettings.OmitXmlDeclaration = true;//删除XmlDeclaration: //xmlWriterSettings.NewLineChars = "\r\n"; //xmlWriterSettings.NewLineHandling = NewLineHandling.None; XmlSerializer xml = new XmlSerializer(type); try { using (XmlWriter xmlWriter = XmlWriter.Create(Stream, xmlWriterSettings)) { //序列化对象 xml.Serialize(xmlWriter, obj, _name); } } catch (InvalidOperationException) { throw; } return Encoding.UTF8.GetString(Stream.ToArray()).Trim(); } #endregion }