【问题标题】:xmlns=''> was not expected. - There is an error in XML document (2, 2)xmlns=''> 不是预期的。 - XML 文档中存在错误 (2, 2)
【发布时间】:2012-10-01 11:36:45
【问题描述】:

我试图反序列化来自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());

【问题讨论】:

  • 当我收到此错误时发生的事情是我将许多对象分别序列化到同一个文件然后尝试将所述 xml 文件反序列化到列表中,修复它只是删除了 xmlns 部分xml 文件,创建一个自定义列表,然后仅序列化该列表,然后我将 xml 文件反序列化为自定义列表。我知道这与你无关,但我将把它留在这里,因为这是我遇到的问题,让我首先考虑这个问题,所以也许它会帮助其他人。

标签: c# .net xml xml-serialization


【解决方案1】:

将 XmlSerializer 声明为

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

够了。

【讨论】:

  • 仅供参考 L.B 是正确的,但如果有父节点,则略有不同。在 xml 中,我正在反序列化父节点是 ,它抛出了异常“
  • 500 赏金正在送给你的伴侣。谢谢。
  • 还请注意,如果您的根属性上有命名空间,您可能需要稍微调整一下 XmlRootAttribute。 xmlRoot.ElementName = reader.Name.Split(':').Last(); xmlRoot.Namespace = reader.NamespaceURI;
【解决方案2】:

您想反序列化 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);
}

【讨论】:

  • 感谢您的宝贵时间。我发现用户 L.B 的回答非常简单实用。
【解决方案3】:

我在将“声明了 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    相关资源
    最近更新 更多