C#反序列化XML时提示XML 文档(1, 1)中有错误
最近在反序列化一个XML时,遇到了如下报错:
XML 文档(1, 1)中有错误。
内部异常
XmlException: 根级别上的数据无效。 第 1 行,位置 1。
看描述应该是XML格式的问题,我把XML复制到新建的控制台程序,反序列化又是可以的。代码如下:
1 internal class Program 2 { 3 static void Main(string[] args) 4 { 5 var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Response>\r\n <Status>200</Status>\r\n <Message>成功</Message>\r\n</Response>"; 6 7 XmlSerializer xmlSerializer = new XmlSerializer(typeof(Response)); 8 using (StringReader sr = new StringReader(xml)) 9 { 10 Response response = (Response)xmlSerializer.Deserialize(sr); 11 } 13 } 14 } 15 16 public class Response 17 { 18 public int Status { get; set; } 19 20 public string Message { get; set; } 21 }
在Stackoverflow上找到一个解决方案,这里分享一下
原因如下:
Each Unicode character in a string is defined by a Unicode scalar value, also called a Unicode code point or the ordinal (numeric) value of the Unicode character. Each code point is encoded using UTF-16 encoding, and the numeric value of each element of the encoding is represented by a Char object.
大意来讲,就是XML里指定的是utf-8编码,.NET内部使用了utf-16编码。
1 <?xml version="1.0" encoding="utf-8"?>
解决方法如下:
使用Utf-8编码获取字节数组,再通过调用Deserialize的重载,将字节数组转换成流传进去。
1 XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); 2 3 var buffer = Encoding.UTF8.GetBytes(xml); 4 using (MemoryStream ms = new MemoryStream(buffer)) 5 { 6 return (T)xmlSerializer.Deserialize(ms); 7 }
参考资料: