27

我试图反序列化来自这个简单 Web 服务的响应

我使用以下代码:

WebRequest request = WebRequest.Create("http://inb374.jelastic.tsukaeru.net:8080/VodafoneDB/webresources/vodafone/04111111");    
WebResponse ws = request.GetResponse();
XmlSerializer s = new XmlSerializer(typeof(string));
string reponse = (string)s.Deserialize(ws.GetResponseStream());
4

3 回答 3

61

将 XmlSerializer 声明为

XmlSerializer s = new XmlSerializer(typeof(string),new XmlRootAttribute("response"));

足够。

于 2012-10-01T11:53:33.597 回答
11

您想要反序列化 XML 并将其视为片段。

这里有一个非常简单的解决方法。我已经根据您的情况对其进行了修改:

var webRequest = WebRequest.Create("http://inb374.jelastic.tsukaeru.net:8080/VodafoneDB/webresources/vodafone/04111111");

using (var webResponse = webRequest.GetResponse())
using (var responseStream = webResponse.GetResponseStream())
{
    var rootAttribute = new XmlRootAttribute();
    rootAttribute.ElementName = "response";
    rootAttribute.IsNullable = true;

    var xmlSerializer = new XmlSerializer(typeof (string), rootAttribute);
    var response = (string) xmlSerializer.Deserialize(responseStream);
}
于 2012-10-01T11:39:09.637 回答
1

我在将“声明了 2 个命名空间的 xml 字符串”反序列化为对象时遇到了同样的错误。

<?xml version="1.0" encoding="utf-8"?>
<vcs-device:errorNotification xmlns:vcs-pos="http://abc" xmlns:vcs-device="http://def">
    <errorText>Can't get PAN</errorText>
</vcs-device:errorNotification>
[XmlRoot(ElementName = "errorNotification", Namespace = "http://def")]
public class ErrorNotification
{
    [XmlAttribute(AttributeName = "vcs-pos", Namespace = "http://www.w3.org/2000/xmlns/")]
    public string VcsPosNamespace { get; set; }

    [XmlAttribute(AttributeName = "vcs-device", Namespace = "http://www.w3.org/2000/xmlns/")]
    public string VcsDeviceNamespace { get; set; }

    [XmlElement(ElementName = "errorText", Namespace = "")]
    public string ErrorText { get; set; }
}

通过将带有[XmlAttribute]的字段添加到 ErrorNotification 类反序列化工作中。

public static T Deserialize<T>(string xml)
{
    var serializer = new XmlSerializer(typeof(T));
    using (TextReader reader = new StringReader(xml))
    {
        return (T)serializer.Deserialize(reader);
    }
}

var obj = Deserialize<ErrorNotification>(xml);
于 2019-12-02T15:52:57.000 回答