【问题标题】:XML Deserialization - xmlns not expectedXML 反序列化 - 不需要 xmlns
【发布时间】:2015-01-27 16:03:06
【问题描述】:

/我尝试反序列化xml文件时出错:

System.InvalidOperationException: There is an error in XML document (2, 2). ---> <MessageIpBNotifGetInventaire xmlns='http://www.idele.fr/XML/Schema/'> was not expected.

我的 XML 中有问题的部分如下所示:

<ns2:MessageIpBNotifGetInventaire xmlns="http://www.fiea.org/types/" xmlns:ns2="http://www.idele.fr/XML/Schema/">

我的班级是这样定义的:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.idele.fr/XML/Schema/")]
[System.Xml.Serialization.XmlRootAttribute("MessageIpBNotifGetInventaire", Namespace = "http://www.idele.fr/XML/Schema/", IsNullable = false)]

public partial class MessageIpBNotifGetInventaire {

这是我的反序列化代码

using (MemoryStream inputStream = new MemoryStream(reponseSpecifique.MessageZip))
            {
                using (ZipFile zipFile = ZipFile.Read(inputStream))
                {
                    zipFile.Save("D:\\Test.zip");
                    foreach (ZipEntry zipEntry in zipFile)
                    {
                        using (MemoryStream outputStream = new MemoryStream())
                        {
                            zipEntry.Extract(outputStream);
                            outputStream.Position = 0;
                            using (StreamReader sr = new StreamReader(outputStream, Encoding.GetEncoding("UTF-8")))
                            {

                                XmlReader reader = XmlReader.Create(outputStream);
                                XmlSerializer serializer = new XmlSerializer(typeof(MessageIpBNotifGetInventaire));
                                MessageIpBNotifGetInventaire messageRetour = (MessageIpBNotifGetInventaire)serializer.Deserialize(reader);
                            }
                        }
                    }
                }
            }

【问题讨论】:

  • 你的课程代码在哪里?

标签: c# xml serialization


【解决方案1】:

问题是XmlRootAttribute 定义中的命名空间与 XML 文档本身中的命名空间不匹配。一个结尾有/,另一个没有。

你可能会想,这些 URL 指向的不是同一个东西,但实际上使用 URL 作为命名空间只是一种约定(我自己不遵循这个约定,我更喜欢使用 urn:companyname:schemas:appname 或类似的东西),并且字符串必须完全匹配。

【讨论】:

  • 感谢您的回答。即使添加 / ,我也会收到错误消息。
  • 我还没有机会再看这个。如果您有比问题中的示例更多的名称,我建议您仔细检查您是否已修复所有元素声明中的名称空间,并查看您是否可以生成Minimal, Complete, and Verifiable example。这样做可能会帮助您发现自己的错误。
猜你喜欢
  • 1970-01-01
  • 2012-04-28
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 2010-12-06
  • 1970-01-01
相关资源
最近更新 更多