首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不应为xmlns=''>。- XML文档(2,2)中存在错误

不应为xmlns=''>。- XML文档(2,2)中存在错误
EN

Stack Overflow用户
提问于 2012-10-01 19:36:46
回答 3查看 48.3K关注 0票数 27

我正在尝试反序列化来自this simple web service的响应

我正在使用以下代码:

代码语言:javascript
复制
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());
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-10-01 19:53:34

将XmlSerializer声明为

代码语言:javascript
复制
XmlSerializer s = new XmlSerializer(typeof(string),new XmlRootAttribute("response"));

就足够了。

票数 61
EN

Stack Overflow用户

发布于 2012-10-01 19:39:10

您希望对XML进行反序列化,并将其视为片段。

有一个非常简单的变通方法可用here。我已经针对您的场景进行了修改:

代码语言:javascript
复制
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);
}
票数 11
EN

Stack Overflow用户

发布于 2019-12-02 23:52:57

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

代码语言:javascript
复制
<?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>
代码语言:javascript
复制
[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类中,可以实现反序列化。

代码语言:javascript
复制
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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12672512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档