这个 C# XML 反序列化代码有什么问题?

What is wrong with this C# XML Deserialization code?

我已经阅读了尽可能多的文章,我以前用这种方式进行过序列化,但我无法弄清楚为什么以下内容无法正常工作。

感谢帮助。

鉴于此代码:

POCO 类 去序列化响应:

[XmlRoot]
public class MyResponseClass
{
    [XmlElement("response")]
    public Response Response { get; set; }
}

[XmlRoot]
public class Response
{
    [XmlElement("error")]
    public Error Error { get; set; }

    [XmlElement("sid")]
    public string Sid { get; set; }
}

[XmlRoot]
public class Error
{
    [XmlElement("error_msg")]
    public string ErrorMessage { get; set; }
}

请求和响应处理代码:

var webClient = _webClientWrapperFactory.Create();
var url = "https://serviceendpoint.com";
var responseString = webClient.DownloadString(url);

MyResponseClass result;
var serializer = new XmlSerializer(typeof(MyResponseClass));
using (var reader = new StringReader(responseString))
{
result = (MyResponseClass) serializer.Deserialize(reader);
}
return result;

Returns 这个回复:

<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><response><error><error_msg>CANNOT_LOGIN</error_msg></error></response>

反序列化尝试抛出此错误:

类型 'System.InvalidOperationException' 的异常发生在 System.Xml.dll 但未在用户代码中处理

附加信息:XML 文档 (1, 57) 中存在错误。

编辑: 内部异常:

{"<response xmlns=''> was not expected."}

我创建了一个 MyResponseClass 的快速实例并将其序列化:

<?xml version="1.0" encoding="utf-16"?>
<MyResponseClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <response>
    <error>
      <error_msg>error message text</error_msg>
    </error>
    <sid>(sid string)</sid>
  </response>
</MyResponseClass>

这就是您的 XML 对于 MyResponseClass 的样子。这是我使用的序列化代码:

MyResponseClass result1 = new MyResponseClass
{
    Response = new Response
    {
        Sid = "(sid string)",
        Error = new Error
        {
            ErrorMessage = "error message text"
        }
    }
};

var serializer = new XmlSerializer(typeof(MyResponseClass));
string serialized = "";

using (StringWriter textWriter = new StringWriter())
{
    serializer.Serialize(textWriter, result1);
    serialized = textWriter.ToString();
}

但这可能不是您想要的。

如果您想坚持使用问题中的 XML,则需要省去 MyResponseClass 并指定 Response 作为 XML 根, 全部小写:

[XmlRoot("response")]
public class Response
{
    [XmlElement("error")]
    public Error Error { get; set; }

    [XmlElement("sid")]
    public string Sid { get; set; }
}

...

var responseString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><response><error><error_msg>CANNOT_LOGIN</error_msg></error></response>";

var serializer2 = new XmlSerializer(typeof(Response));

//using (StringWriter textWriter = new StringWriter())
//{
//    serializer2.Serialize(textWriter, result1.Response);
//    responseString = textWriter.ToString();
//}

Response result;
using (var reader = new StringReader(responseString))
{
    result = (Response)serializer2.Deserialize(reader);
}