[英]Error while deserializing xml string into object using XMLSerializer in C#
[英]c# Error while deserializing xml to object
我需要測試通過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 =“”
您可以嘗試在根類XmlData
添加名稱空間:
[XmlRoot(ElementName = "XmlData", Namespace = "http://schemas.datacontract.org/2004/07/Common.Util")]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.