我正在尝试反序列化来自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());发布于 2012-10-01 19:53:34
将XmlSerializer声明为
XmlSerializer s = new XmlSerializer(typeof(string),new XmlRootAttribute("response"));就足够了。
发布于 2012-10-01 19:39: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);
}发布于 2019-12-02 23:52:57
我在将“声明了2个命名空间的xml字符串”反序列化为object时也遇到了同样的错误。
<?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);https://stackoverflow.com/questions/12672512
复制相似问题