遇到C# XML Serialization序列化成字符串含有65279问题。解决方案如下...
这行是最重要的
Encoding = new UTF8Encoding(false), // Disable to provide a Unicode byte order mark
附完整代码:
public interface IXmlFileSerializer { void Serialize<T>(object obj, string filePath); T Deserialize<T>(string filePath); }
public interface IXmlStringSerializer { string Serialize<T>(object obj); T Deserialize<T>(string xmlString); }
public class XmlFileSerializer : IXmlFileSerializer { private readonly IXmlStringSerializer _xmlStringSerializer; public XmlFileSerializer() : this(new XmlStringSerializer()) { } public XmlFileSerializer(IXmlStringSerializer xmlStringSerializer) { if (xmlStringSerializer == null) throw new ArgumentNullException("xmlStringSerializer"); _xmlStringSerializer = xmlStringSerializer; } public void Serialize<T>(object obj, string filePath) { var xmlString = _xmlStringSerializer.Serialize<T>(obj); File.WriteAllText(filePath, xmlString); } public T Deserialize<T>(string filePath) { if (!File.Exists(filePath)) throw new FileNotFoundException(string.Format("The file '{0}' doesn't exist", filePath)); var xmlString = File.ReadAllText(filePath); return _xmlStringSerializer.Deserialize<T>(xmlString); } }
public class XmlStringSerializer : IXmlStringSerializer { public string Serialize<T>(object obj) { var type = typeof(T); if (obj.GetType() != type) throw new Exception("The object to serialize is not with expected type."); using (var stream = new MemoryStream()) { var writer = CreateXmlWriter(stream); var serializer = new XmlSerializer(type); serializer.Serialize(writer, obj, CreateXmlSerializerNamespaces()); return Encoding.UTF8.GetString(stream.ToArray()); } } private static XmlWriter CreateXmlWriter(Stream stream) { var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), Indent = true }; return XmlWriter.Create(stream, settings); } private static XmlSerializerNamespaces CreateXmlSerializerNamespaces() { var namespaces = new XmlSerializerNamespaces(); namespaces.Add(string.Empty, string.Empty); return namespaces; } public T Deserialize<T>(string xmlString) { using (var reader = new StringReader(xmlString)) { var type = typeof(T); var serializer = new XmlSerializer(type); return (T)serializer.Deserialize(reader); } } }