views:

1220

answers:

2

I was just wondering if there are any good work-arounds for Deserializing private fields/properties using XmlSerializer.Deserialize() ?

Currently, I Deserialize my XML to a simple disposable type with all public properties, then I load the complex type that has private properties like this:

ComplexType complex = new ComplexType(SimpleType);

and the constructor of ComplexType looks like this:

public ComplexType(SimpleType simpleType){
    this.Property1 = simpleType.Property1;
    this.Property2 = simpleType.Property2;
    .....

}

Anyone has a better way of doing this?

+1  A: 

You can have ComplexType implement the IXmlSerializable interface. This exposes methods for serialization and deserialization, so you can fill the private members of complextype in these methods.

Check out MSDN here: http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx for an example showing an implementation of the IXmlSerializable interface that serializes a private field.

+1  A: 

Note that another option is to use DataContractSerializer (.NET 3.0) - this supports serialization of private members (properties or fields).

Marc Gravell