I have an object InputFile
that has arrays and objects to hold the contents of a file. I also have ABCFile
and XYZFile
that are both inhe
Try
[XmlArray]
[XmlArrayItem(ElementName="ABCFile", Type=typeof(ABCFile))]
[XmlArrayItem(ElementName="XYZFile", Type=typeof(XYZFile))]
public List<InputFile> InputFileList
{
get;
set;
}
This will indicate the serializer that, even though this is a List of InputFile, there will be two derived types that will be stored in this list. It's likely to make it use specific version of methods for each one.
If it fail, let me know.
Edit based on your comment
I don't see how this can be happing.
I tested it the following classes:
public class InputFile
{
public String InputfileCommonProperty { get; set; }
}
public class ABCFile : InputFile
{
public String ABCSpecificProperty { get; set; }
}
public class XYZFile : InputFile
{
public String XYZSpecificProperty { get; set; }
}
public class InputFileHolder
{
public InputFileHolder()
{
InputFileList = new List<InputFile>();
}
[XmlArray]
[XmlArrayItem(ElementName = "ABCFile", Type = typeof(ABCFile))]
[XmlArrayItem(ElementName = "XYZFile", Type = typeof(XYZFile))]
public List<InputFile> InputFileList { get; set; }
}
My main program looks like:
static void Main(string[] args)
{
InputFileHolder fileHolder = new InputFileHolder();
fileHolder.InputFileList.Add(
new ABCFile()
{
InputfileCommonProperty = "This is a common property",
ABCSpecificProperty = "This is a class specific property"
});
XmlSerializer serializer = new XmlSerializer(typeof(InputFileHolder));
MemoryStream memoryStream = new MemoryStream();
serializer.Serialize(memoryStream, fileHolder);
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
String serializedString = enc.GetString(memoryStream.ToArray());
}
And in the end, serializedString's content is:
<?xml version="1.0"?>
<InputFileHolder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<InputFileList>
<ABCFile>
<InputfileCommonProperty>This is a common property</InputfileCommonProperty>
<ABCSpecificProperty>This is a class specific property</ABCSpecificProperty>
</ABCFile>
</InputFileList>
</InputFileHolder>
You see? The serializer knows it's a ABCFile not a generic InputFile.