Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am getting an error when trying to XML serialize an object

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type ProfileChulbul was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
   at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterProfileDefinitionExportHolder.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType)

if you see 'ProfileChulbul' is an object, I am trying to serialize

like image 838
BreakHead Avatar asked Feb 07 '11 16:02

BreakHead


1 Answers

This happens when the type you're serializing has a property of a type that is not statically known to the serializer instance. For example, if the type ProfileChulbul has a base type, which is how it is referenced from what you're serializing, the serializer won't know how to work with it.

You have a couple options for resolving this problem:

  • Add the [XmlInclude(typeof(ProfileChulbul))] attribute (and additional attributes for any other types that will be used) to ProfileChulbul's base class

  • Modify the class you use for serialization to use generics instead of Object

  • Pass typeof(ProfileChulbul) (and any other types that will be used) into the serializer constructor at runtime, like so:

    var knownTypes = new Type[] { typeof(ProfileChulbul), typeof(ProfileSomethingElse) };

    var serializer = new XmlSerializer(typeof(TheSerializableType), knownTypes);

like image 97
Daniel Schaffer Avatar answered Sep 21 '22 00:09

Daniel Schaffer