XML Deserialization of Inherited Objects

后端 未结 1 1448
[愿得一人]
[愿得一人] 2021-01-28 03:34

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

1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-28 04:10

    Try

    [XmlArray]
    [XmlArrayItem(ElementName="ABCFile", Type=typeof(ABCFile))]
    [XmlArrayItem(ElementName="XYZFile", Type=typeof(XYZFile))]
    public List 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();
        }
    
        [XmlArray]
        [XmlArrayItem(ElementName = "ABCFile", Type = typeof(ABCFile))]
        [XmlArrayItem(ElementName = "XYZFile", Type = typeof(XYZFile))]
        public List 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:

    
    
      
        
          This is a common property
          This is a class specific property
        
      
    
    

    You see? The serializer knows it's a ABCFile not a generic InputFile.

    0 讨论(0)
提交回复
热议问题