xmlns=''> was not expected. - There is an error in XML document (2, 2)

佐手、 提交于 2019-12-18 18:41:22

问题


Im trying to deserialize the response from this simple web service

Im using the following code:

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());

回答1:


Declaring XmlSerializer as

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

is enough.




回答2:


You want to deserialize the XML and treat it as a fragment.

There's a very straightforward workaround available here. I've modified it for your scenario:

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);
}



回答3:


I had the same error with Deserialize "xml string with 2 namespaces declared" into 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; }
}

By adding field with [XmlAttribute] into ErrorNotification class deserialization works.

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/xmlns-was-not-expected-there-is-an-error-in-xml-document-2-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!