【问题标题】:How to deserialize an Xml Fragment using the XML Reader如何使用 XML Reader 反序列化 Xml 片段
【发布时间】:2009-03-16 20:38:38
【问题描述】:

我正在尝试反序列化 Xml 片段。我快到了,但它会抛出一个错误,因为它不需要第一个元素。流中的 XML 示例如下:

  <Project xmlns="http://schemas.datacontract.org/2004/07/Swissmod.Service.Model" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <ClientID>1</ClientID> 
  <Created>2009-03-16T20:34:57.022167+00:00</Created> 
  <ID>22</ID> 
  <LastModified>2009-03-11T20:34:57.022167+00:00</LastModified> 
  <ProjectDescription>Description here</ProjectDescription> 
  <ProjectTitle>Poject title</ProjectTitle> 
  <UserID>5</UserID> 
  <Version>1234567</Version> 
  </Project>

我正在使用以下代码进行反序列化:

  XmlSerializer serializer = new XmlSerializer(typeof(Project));
  XmlReaderSettings settings = new XmlReaderSettings();
  settings.ValidationFlags = XmlSchemaValidationFlags.None;
  settings.ValidationType = ValidationType.None;
  settings.ConformanceLevel = ConformanceLevel.Auto;
  settings.IgnoreProcessingInstructions = true;
  settings.NameTable = new NameTable();
  settings.NameTable.Add("http://schemas.datacontract.org/2004/07/Swissmod.Service.Model");
  XmlReader reader = XmlReader.Create(wresp.GetResponseStream(),settings);
  Project p = (Project)serializer.Deserialize(reader);

但是上面抛出了以下错误:

There is an error in XML document (1, 2).
"<Project xmlns='http://schemas.datacontract.org/2004/07/Swissmod.Service.Model'> was not expected."

有人知道如何使用 XML 阅读器读取 XML 片段吗?

【问题讨论】:

    标签: c# xml serialization


    【解决方案1】:

    在您的 Project 类定义中,您是否尝试过在 XmlRoot 属性中指定命名空间?

    【讨论】:

    • 大声笑,就是这样!!非常感谢你花时间陪伴。添加该属性使其成为一种享受。谢谢你。 :-)
    • 如果在 XmlRoot 属性中指定命名空间Project 会是什么样子?
    猜你喜欢
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多