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

时间:2017-05-23 13:58:36

标签: c# xml serialization deserialization xml-deserialization

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

协助表示赞赏。

鉴于此代码:

解除反应的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;

返回此回复:

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

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

类型&#39; System.InvalidOperationException&#39;的例外情况发生在System.Xml.dll中但未在用户代码中处理

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

编辑: 内部例外:

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

1 个答案:

答案 0 :(得分:1)

我创建了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>

这就是MyResponseClass的XML应该是什么样的。这是我使用的序列化代码:

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);
}