代码之家  ›  专栏  ›  技术社区  ›  atsjoo

通过继承将列表<T>序列化为XML

  •  4
  • atsjoo  · 技术社区  · 17 年前

    Profile类型理想情况下应该是抽象的,但事实并非如此,因为XML序列化需要一个无参数的构造函数。Profiles属性包含类型为“IncomeProfile”、“CostProfile”和“InvestmentProfile”等的项,这些项当然都继承自Profile。

    [XmlInclude(typeof(IncomeProfile))]
    public List<Profile> Profiles { get; set; }
    

    while(reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "Profile")
        {
            String type = reader["Type"];
            var project = (Profile)Activator.CreateInstance(Type.GetType(type));
            project.ReadXml(reader);
    
            reader.Read();
            this.Profiles.Add(p2);
        }
    

    2 回复  |  直到 17 年前
        1
  •  10
  •   Marc Gravell    17 年前

    您可以使用多个include属性,尽管它们通常针对类型本身进行设置:

    using System;
    using System.Collections.Generic;
    using System.Xml.Serialization;
    [XmlInclude(typeof(IncomeProfile))]
    [XmlInclude(typeof(CostProfile))]
    [XmlInclude(typeof(InvestmentProfile))]
    public class Profile {
        public string Foo { get; set; }
    }
    public class IncomeProfile : Profile {
        public int Bar { get; set; }
    }
    public class CostProfile : Profile { }
    public class InvestmentProfile : Profile { }
    static class Program {
        static void Main() {
            List<Profile> profiles = new List<Profile>();
            profiles.Add(new IncomeProfile { Foo = "abc", Bar = 123 });
            profiles.Add(new CostProfile { Foo = "abc" });
            new XmlSerializer(profiles.GetType()).Serialize(Console.Out, profiles);
        }
    }
    
        2
  •  3
  •   John Saunders    17 年前

    您只需使用多个[XmlInclude]属性。这很有效。