使用XmlSerializer读取UTF-16编码的XML文件

时间:2010-11-23 08:10:37

标签: .net xml xmlserializer

我正在调用WebService并获取从WebMethod返回的字符串。该字符串是一个序列化为XML的对象,应使用System.Xml.XmlSerializer进行反序列化。

我的问题是第一行表示文档是UTF-16编码的:

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

因此,在反序列化时,我收到错误:

There is an error in XML document (0, 0).

它确实可以用于执行string.Replace(“utf-16”,“utf-8”),但必须有一个干净的方法让XmlSerializer知道吗?

1 个答案:

答案 0 :(得分:5)

这不应该影响任何事情 - 以下工作正常:

using System;
using System.IO;
using System.Xml.Serialization;

[XmlRoot("someType")]
public class Test {
    [XmlAttribute("hello")]
    public string Value { get; set; }
}
static class Program {   
    static void Main()     {
        string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
<someType hello=""world""/>";
        var ser = new XmlSerializer(typeof(Test));
        Test obj;
        using (var reader = new StringReader(xml)) {
            obj = (Test)ser.Deserialize(reader);
        }
        Console.WriteLine(obj.Value);
    }

}
相关问题