XML反序列化编码问题

时间:2016-09-21 13:24:34

标签: c# xml xml-serialization xml-deserialization

我已经搜索了很多,无法找到解决方案而无法确定正确的方法

我将一个对象序列化为xml字符串,并使用c#将其反序列化回一个对象。序列化后的XML字符串添加了一个领先的?当我将它解释回对象时,我收到错误XML文档中存在错误(1,1)

?<?xml version="1.0" encoding="utf-16"?>

序列化代码:

 string xmlString = null;
 MemoryStream memoryStream = new MemoryStream();
 XmlSerializer xs = new XmlSerializer(typeof(T));
 XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
 ns.Add("abc", "http://example.com/abc/");
 XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream,Encoding.Unicode);
xs.Serialize(xmlTextWriter, obj, ns);
 memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
 xmlString = ConvertByteArrayToString(memoryStream.ToArray());

ConvertByteArrayToString:

   UnicodeEncoding encoding = new UnicodeEncoding();
    string constructedString = encoding.GetString(characters);

反序列化代码:

XmlSerializer ser = new XmlSerializer(typeof(T));
StringReader stringReader = new StringReader(xml);
XmlTextReader xmlReader = new XmlTextReader(stringReader);
object obj = ser.Deserialize(xmlReader);
xmlReader.Close();
stringReader.Close();
return (T)obj;

我想知道我在编码方面做错了什么,我需要一个适用于大多数情况的解决方案。感谢

2 个答案:

答案 0 :(得分:0)

使用以下函数进行序列化和反序列化

public static string Serialize<T>(T dataToSerialize)
{
    try
    {
        var stringwriter = new System.IO.StringWriter();
        var serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(stringwriter, dataToSerialize);
        return stringwriter.ToString();
    }
    catch
    {
        throw;
    }
}

public static T Deserialize<T>(string xmlText)
{
    try
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
    }
    catch
    {
        throw;
    }
}

答案 1 :(得分:0)

您的序列化XML在开头包含Unicode byte-order mark,这就是解串器失败的地方。

要删除BOM,您需要创建不同版本的编码来抑制BOM而不是使用默认的Encoding.Unicode

new XmlTextWriter(memoryStream, new UnicodeEncoding(false, false))

此处第二个false可防止BOM被添加到字符串之前。