2013-02-14 52 views
1

我在將對象反序列化爲XML時遇到了一些麻煩。我想反序列化沒有空構造函數的東西,因此我需要使用BinaryFormatter?我有:將對象二進制反序列化爲XML?

  • 一個由我想將反序列化爲XML的類組成的DLL。
  • 從反映類型我可以看出它沒有無參數的構造函數。
  • 該類包含一些沒有空構造函數的屬性。

我的問題是,是否有可能將此類反序列化爲XML?我沒有找到一個辦法,其中我用:

  • 的BinaryFormatter
  • 加載的內容爲使用一個FileStream寫其內容的流
  • ,但結束了提前垃圾

感謝。我發現了一個名爲FormatterServices的東西......但不知道你是否可以將它與XmlSerializer結合使用?

+1

您是否嘗試過** [DataContractSerializer的(http://msdn.microsoft.com/en-us /library/system.runtime.serialization.datacontractserializer.aspx)**?我不確定它是否可以序列化任何類(沒有使用DataMember裝飾DataContract及其成員) – 2013-02-14 10:18:14

+0

這被稱爲序列化... – 2013-02-14 10:19:57

+0

@HonzaBrestan不錯,似乎工作,但是你得到一些奇怪的看XML ...任何想法如何消除你得到每個領域的怪異標籤? – 2013-02-14 10:32:42

回答

0
  1. 將二進制數據反序列化回對象。

  2. 將您的對象複製到代理對象中。

  3. Xml序列化您的代理對象。

假設你原來的非XML序列化對象的類型是 「富」

[XmlRoot] 
public class FooSurrogate { 

    public FooSurrogate() { }; // note the empty constructor for xml deserialization 

    public FooSurrogate(Foo foo) { // this constructor is used in step 2 
      // in here you copy foo's state into this object's state 
      this.Prop1 = foo.Prop1; // this prop can be copied directly 
      this.Bar = new BarSurrogate(foo.Bar); // this prop needs a surrogate as well 
    } 

    [XmlAttribute] // note your surrogate can be used to xml-format too! 
    public string Prop1 { get; set; } 

    [XmlElement] 
    public BarSurrogate Bar { get; set; } 

} 

public class BarSurrogate { 
... 
}