2014-05-13 64 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

相關問題