using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; namespace Ds.Module.WeChat.Utilities { /// XML 工具类 public static class XmlUtility { /// 反序列化 /// XML字符串 /// public static object Deserialize(string xml) { try { using (StringReader stringReader = new StringReader(xml)) return new XmlSerializer(typeof(T)).Deserialize((TextReader)stringReader); } catch (Exception ex) { Console.WriteLine((object)ex); return (object)null; } } /// 反序列化 /// /// public static object Deserialize(Stream stream) => new XmlSerializer(typeof(T)).Deserialize(stream); /// /// 序列化 /// 说明:此方法序列化复杂类,如果没有声明XmlInclude等特性,可能会引发“使用 XmlInclude 或 SoapInclude 特性静态指定非已知的类型。”的错误。 /// /// 对象 /// public static string Serializer(T obj) { MemoryStream memoryStream = new MemoryStream(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); try { xmlSerializer.Serialize((Stream)memoryStream, (object)obj); } catch (InvalidOperationException) { throw; } memoryStream.Position = 0L; StreamReader streamReader = new StreamReader((Stream)memoryStream); string end = streamReader.ReadToEnd(); streamReader.Dispose(); memoryStream.Dispose(); return end; } /// 序列化将流转成XML字符串 /// /// public static XDocument Convert(Stream stream) { if (stream.CanSeek) stream.Seek(0L, SeekOrigin.Begin); using (XmlReader reader = XmlReader.Create(stream)) return XDocument.Load(reader); } /// 序列化将流转成XML字符串 /// /// public static string ConvertToString(Stream stream) { StreamReader reader = new StreamReader(stream); string sHtml = reader.ReadToEnd(); return sHtml; } } }