【问题标题】:DataContractSerializer cannot deserialize after namespace changed命名空间更改后 DataContractSerializer 无法反序列化
【发布时间】:2014-07-01 01:48:10
【问题描述】:

我有 50 个课程标有DataContractAttribute

这些类形成一个巨大的层次树,使用DataContractSerializer 将其序列化/反序列化为xml。

它们都指定了一个自定义数据契约命名空间[DataContract(Namespace="http://example.com")],除了我错过的 3 个类。

// Old class definitions 
[DataContract(IsReference=true)]  // <-- forgot ns
public class Type1{}
[DataContract(IsReference=true)] // <-- forgot ns
public class Type2{}
[DataContract(IsReference=true)] // <-- forgot ns
public class Type3{}
[DataContract(IsReference=true, Namespace="http://example.com")] // <-- 47 more like this
public class Type4{} 

我希望这 3 个类使用与其他 47 个类相同的数据契约命名空间。

更改后,我之前保存的所有 xml 都无法加载。

// Changed to:
[DataContract(IsReference=true, Namespace="http://example.com")] // <-- changed ns
public class Type1{} 
[DataContract(IsReference=true, Namespace="http://example.com")] // <-- changed ns
public class Type2{} 
[DataContract(IsReference=true, Namespace="http://example.com")] // <-- changed ns
public class Type3{} 
[DataContract(IsReference=true, Namespace="http://example.com")]
public class Type4{}

我试过这个方法:

DataContractSerializer - change namespace and deserialize file bound to old namespace

但是有一个SerializationExceptionDeserialized object with reference id 'i5' not found in stream.

如何对命名空间更改之前之后保存的 xml 进行反序列化?

【问题讨论】:

    标签: c# namespaces datacontractserializer


    【解决方案1】:

    我会亲自更改数据合同,然后创建一个脚本来解析以前保存的 xml 以添加命名空间信息。快速简单。

    类似于将 xmls 加载为字符串然后调用:

    xmlstr=xmlstr.Replace("<Type1>", "<Type1 xmlns:Namespace=\"http://example.com\">");
    

    或者可能创建两个类(一个使用旧命名空间,一个使用新命名空间)创建一个映射方法,以便您可以基于旧命名空间反序列化旧 xml,并在映射到新命名空间后将它们序列化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      • 2021-07-02
      • 1970-01-01
      • 2018-05-09
      相关资源
      最近更新 更多