【问题标题】:Deserialize object binary to XML?将对象二进制反序列化为 XML?
【发布时间】:2013-02-14 10:15:45
【问题描述】:

我在将对象反序列化为 XML 时遇到了一些问题。我正在尝试反序列化没有空构造函数的东西,因此我需要使用 BinaryFormatter?我有:

  • 一个 DLL,它包含一个我想反序列化为 XML 的类。
  • 从反映类型可以看出它没有无参构造函数。
  • 此类包含一些属性,其中一些属性也没有空构造函数。

我的问题是,是否可以将此类反序列化为 XML?我确实找到了一种使用方法:

  • BinaryFormatter
  • 将内容加载到流中
  • 使用 FileStream 写入其内容,但结果是垃圾

提前致谢。我找到了一个叫做 FormatterServices 的东西……但不知道你是否可以将它与 XmlSerializer 结合使用?

【问题讨论】:

  • 你试过DataContractSerializer吗?我不确定它是否可以序列化任何类(没有用 DataContract 及其成员用 DataMember 装饰)
  • 这叫序列化...
  • @HonzaBrestan 看起来不错,但是您会得到一些看起来很奇怪的 XML...任何想法如何消除您为每个字段获得的奇怪标签?
  • 只有当你可以访问类本身或者你可以包装它——你需要用我提到的属性来装饰它——你可以使用它们来更改标签名称。

标签: c# xml deserialization xmlserializer binaryformatter


【解决方案1】:
  1. 将二进制数据反序列化回对象。

  2. 将您的对象复制到代理对象中。

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

假设你原来的非 xml 可序列化对象的类型是“Foo”

[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 { 
...
}

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 2011-03-16
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    相关资源
    最近更新 更多