XmlHelper.cs
public class XMLHelper { public static string Serialize<T>(T entity, Encoding encoding = null) { StringBuilder sb = new StringBuilder(); XmlSerializer serializer = new XmlSerializer(typeof(T)); if (encoding == null) { using (TextWriter tw = new StringWriter(sb)) serializer.Serialize(tw, entity); return sb.ToString(); } using (MemoryStream ms = new MemoryStream()) using (StreamWriter sw = new StreamWriter(ms, encoding)) { serializer.Serialize(sw, entity); byte[] bytes = ms.ToArray(); return encoding.GetString(bytes, 0, bytes.Length); } } public static void AppendSerializeNameSpace(XmlDocument doc) { if (string.IsNullOrWhiteSpace(doc.InnerText)) return; if (!doc.DocumentElement.HasAttribute("xmlns:xsi")) doc.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); if (!doc.DocumentElement.HasAttribute("xmlns:xsd")) doc.DocumentElement.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); } public static void SerializeToFile<T>(string filePath, T obj, string rootName = null) { using (StreamWriter sw = new StreamWriter(filePath)) { XmlSerializer serializer = string.IsNullOrWhiteSpace(rootName) ? new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(rootName)); serializer.Serialize(sw, obj); } } public static T DeserializeFromFile<T>(string filePath) { using (StreamReader sr = new StreamReader(filePath)) { var setting = new XmlReaderSettings
{
CheckCharacters = false//保留等于空格的字符串值,默认会忽略空格而赋值为null,比如<demo> </demo>,解析默认会demo=null,CheckCharacters=false时demo=" "
};
using (XmlReader r = XmlReader.Create(sr, setting))
{ XmlSerializer serializer = new XmlSerializer(typeof(T)); return (T)serializer.Deserialize(r);
} } } public static T Deserialize<T>(string xmlString) { T cloneObject = default(T); StringBuilder buffer = new StringBuilder(); buffer.Append(xmlString); XmlSerializer serializer = new XmlSerializer(typeof(T)); using (TextReader reader = new StringReader(buffer.ToString())) { Object obj = serializer.Deserialize(reader); cloneObject = (T)obj; } return cloneObject; } }