views:

32

answers:

1

I need to serialize dynamically loaded types' classes using XMLSerializer.

When using XML serializer non initialized values are not being serialized. I dont have control over the assemblies I am working with so can not use XML attributes for specifying default values on properties. So I think I need to set all properties and sub properties to their default values recursively and then serialize. ( Please let me know if there is any better way )

Followed this :

Activator.CreateInstance(propType);

but above line complains about not having a parameterless constructor for some types.

Tried this : subObject = FormatterServices.GetUninitializedObject(propType); but this one gives an error "value was invalid" with no inner exception.

Please let me know if you need any further information.

+1  A: 

If the types in question don't have public parameterless constructors, you'll struggle. You can get around the attributes issue by using the constructor overload that accepts a XmlAttributeOverrides object, which you can use to fully configure the serializer including the default value (via XmlAttributes.XmlDefaultValue), but some things you can't do - and get around the constructor limitation is one of them.

What is the scenario here?

  • if you want xml, then I would introduce a DTO layer: some objects that look like the ones you're talking about, but are simple and under your control. Ideal for XmlSerializer. You then write code to map between the two
  • if you just want serialization (and xml is an implementation detail) then there are other serializers that may help. DataContractSerializer or protobuf-net, for example; either would be more versatile here.
Marc Gravell