c#将xml反序列化为对象时出错

时间:2017-10-09 13:13:37

标签: c# xml deserialization

我需要测试通过post http请求发送xml的应用程序。所以我发送给自己并尝试去实现。我得到“XML文档中存在错误(1,2)。”我可以使用收到的xml字符串创建XmlDocument,因此xml是正确的。我想我得到了例外,因为我从不同的源创建了模式,即我将xml的类复制到另一个应用程序中,使用该应用程序创建了模式,然后我从这个模式创建了类。现在我创建了一个简单的服务器,它通过http接收xml并尝试去实现它并在那里复制生成的类。这是代码:

static void Main(string[] args)
        {
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add(@"http://127.0.0.1:123/ololo/");
            listener.Start();
            var context = listener.GetContext();
            var xmlstring = string.Empty;

            using (var sr = new StreamReader(context.Request.InputStream))
            {
                xmlstring = sr.ReadToEnd();
            }
            XmlDocument xmlka = new XmlDocument();
            xmlka.LoadXml(xmlstring);
            XmlSerializer serializer = new XmlSerializer(typeof(XmlData));
            MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlstring));
            try
            {
                XmlData resultingMessage = (XmlData)serializer.Deserialize(memStream);
            }
            catch(Exception ex)
            {

            }
        }

堆栈追踪:

   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
   at ConsoleApplication1.Program.Main(String[] args) in c:\\users\\jamil\\documents\\visual studio 2015\\Projects\\ConsoleApplication1\\ConsoleApplication1\\Program.cs:line 45

InnerException消息:

<XmlData xmlns='http://schemas.datacontract.org/2004/07/Common.Util'> was not expected.

生成的类中的所有索引如下所示:

   // <auto-generated>
    //     This code was generated by a tool.
    //     Runtime Version:4.0.30319.42000
    //
    //     Changes to this file may cause incorrect behavior and will be lost if
    //     the code is regenerated.
    // </auto-generated>
    //------------------------------------------------------------------------------

    // 
    // This source code was auto-generated by xsd, Version=4.6.1055.0.
    // 


    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]

令我困惑的是Namespace =“”

1 个答案:

答案 0 :(得分:2)

您可以尝试在根类XmlData添加命名空间:

[XmlRoot(ElementName = "XmlData", Namespace = "http://schemas.datacontract.org/2004/07/Common.Util")]