I get an error when trying to XML serialize an object

System.Web.Services.Protocols.SoapException: The server could not process the request. ---> System.InvalidOperationException: An error occurred while generating the XML document. ---> System.InvalidOperationException: Type ProfileChulbul was not expected. Use the XmlInclude or SoapInclude attribute to indicate types that are not known statically. in System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive (String name, String ns, Object o, Boolean xsiType) in Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterProfileDefinitionExportHolder.Write1_Object (String nleable String, null String )

If you see that "ProfileChulbul" is an object, I'm trying to serialize

Any idea why so?

Thanx

+4
source share
2 answers

This happens when the type you serialize has a type property that is not statically known to the serializer instance. For example, if the ProfileChulbul type has a base type referenced by what you serialize, the serializer does not know how to work with it.

You have several options for solving this problem:

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

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

  • Pass typeof(ProfileChulbul) (and any other types that will be used) to the serializer constructor at run time, for example:

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

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

+17
source

Based on the stacktrace part "Use the XmlInclude or SoapInclude attribute to specify types that are not statically known", I would put it, are you trying to serialize an interface or a collection of interfaces? Xml Serialization does not allow this; try marking the interface with XmlInclude attributes.

+1
source

Source: https://habr.com/ru/post/1338742/


All Articles