I'm having severe headaches trying to deserialize an XML into an auto-generated proxy class with derived types.
This is my scenario (working with Xml.Serialization
)
One WCF 4.0 service sharing (as part of the contract) these type:
[XmlRootAttribute(Namespace = "", IsNullable = false)]
public class InstallerConfig
{
[XmlArray]
[XmlArrayItem(typeof(FileExistsRequisite))]
[XmlArrayItem(typeof(RegistryKeyExistsRequisite))]
public List<ModuleRequisite> Prerequisites { /* getter and setter */ }
...
}
FileExistsRequisite
and RegistryKeyExistsRequisite
are both derived from base ModuleRequisite
. All of them are defined as follows:
[XmlInclude(typeof(FileExistsRequisite))]
[XmlInclude(typeof(RegistryKeyExistsRequisite))]
public class ModuleRequisite
{
/* some properties here */
}
public class FileExistsRequisite : ModuleRequisite
{
/* some properties here */
}
public class RegistryKeyExistsRequisite : ModuleRequisite
{
/* some properties here */
}
If I try to serialize and then deserialize an InstallerConfig
instance it just work (both serialization and deserialization work as expected).
This is the resultant XML file:
<?xml version="1.0" encoding="utf-8"?>
<InstallerConfig xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Prerequisites>
<RegistryKeyExistsRequisite>
<RequisiteOrder>1</RequisiteOrder>
<!-- Some other elements with their values -->
</RegistryKeyExistsRequisite>
<FileExistsRequisite>
<RequisiteOrder>2</RequisiteOrder>
<!-- Some other elements with their values -->
</FileExistsRequisite>
</Prerequisites>
</InstallerConfig>
However, in the other hand I have a NET 2.0 WinForms Application with WCF referenced by a web reference. When I try to deserialize previously serialized XML file:
XmlSerializer serializer = new XmlSerializer(typeof(WCFWebReference.InstallerConfig));
XmlTextReader stream = new XmlTextReader("deserializedXML.xml");
WCFWebReference.InstallerConfig desInstallerConfig = (WCFWebReference.InstallerConfig)serializer.Deserialize(stream);
Created desInstallerConfig
object has an empty array of ModuleRequisite
objects (MyNamespace.WCFWebReference.ModuleRequisite[0]
) as value for Prerequisite
field, when XML actually has two elements both derived from ModuleRequisite.
What am I doing wrong? So much frustrated with this trouble :-(
Thanks in advance.