【问题标题】:What causes this error deserializing XML in C#?是什么导致在 C# 中反序列化 XML 时出现此错误?
【发布时间】:2019-02-15 18:18:56
【问题描述】:

尽管在我的类中的 XMLType 和 XMLRoot 属性上列出了此命名空间,但在 C# 中反序列化 XML 时出现以下错误。

<ProductRegistrationInterface xmlns='http://www.4cs.com/CLMSchema'> was not expected.

XML 如下所示:

  <?xml version="1.0"?>
  <ns4CS:ProductRegistrationInterface 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:ns4CS="http://www.4cs.com/CLMSchema">
    <ns4CS:MessageHeader>
      <TargetReference>Some Value</TargetReference>
    </ns4CS:MessageHeader>
    <ProductRegistrations>
      <ProductRegistration>...</ProductRegistration>
      <ProductRegistration>...</ProductRegistration>
      <ProductRegistration>...</ProductRegistration>
    </ProductRegistrations>
  </ns4CS:ProductRegistrationInterface>

ProductRegistrationInterface 类如下所示:

[XmlType(AnonymousType = true, Namespace = "http://www.4cs.com/CLMSchema")]
[XmlRoot(Namespace = "http://www.4cs.com/CLMSchema", IsNullable = false)]
public class ProductRegistrationInterface
{
    /// <summary>
    /// Collection of <see cref="ProductRegistration"/> class.
    /// </summary>
    [XmlArray(Namespace = "")]
    [XmlArrayItem(nameof(ProductRegistration), IsNullable = false)]
    public ProductRegistration[] ProductRegistrations { get; set; }        
}

最后是我正在使用的代码:

XmlSerializer xs = new XmlSerializer(typeof(ProductRegistrationInfo));
StreamReader sr = new StreamReader(@"Test.xml");
ProductRegistrationInfo s = (ProductRegistrationInfo)xs.Deserialize(sr);
sr.Close();

我错过了什么?

【问题讨论】:

  • 该错误使用的引号 (') 与发布的代码 (") 不同。你能同时检查一下吗?
  • 我认为错误消息在帖子中的显示方式存在问题。我现在已经更正了。

标签: c# xml xml-serialization xmlserializer


【解决方案1】:

类型不匹配:您尝试反序列化为 ProjectRegistrationInterface 类型的实例,但使用为 ProductRegistrationInfo 类型创建的序列化程序。

【讨论】:

  • 就是这样。我不知道我之前怎么没看到。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
相关资源
最近更新 更多