我正在尝试从this simple web service
反序列化响应我使用以下代码:
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());
答案 0 :(得分:51)
将XmlSerializer声明为
XmlSerializer s = new XmlSerializer(typeof(string),new XmlRootAttribute("response"));
就够了。
答案 1 :(得分:10)
您希望反序列化XML并将其视为片段。
有一个非常简单的解决方法here。我已根据您的情况对其进行了修改:
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);
}
答案 2 :(得分:0)
我在将“已声明2个命名空间的xml字符串的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);