2014-05-13 48 views
2

我有50个类标记为DataContractAttributeDataContractSerializer无法在名称空间更改后反序列化

这些类形成一个巨大的层次树,使用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{} 

我希望这三个类可以使用与其他47个类相同的datacontract命名空间。

更改后,我以前保存的所有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命名空间变化后和以前保存

回答

1

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

喜欢的东西装个XML作为字符串,然后美其名曰:

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

也许创建两个类(一个使用旧名称空间和一个新)创建一个映射方法,这样就可以反序列化的旧个XML基于旧的名称空间并在与新的名称空间映射之后对其进行序列化。

+0

简单的解决方案,工作得很好。 – jayars

相关问题