包含基本和派生类型对象的列表的XML序列化

时间:2018-09-26 14:03:29

标签: c# xml-serialization

我正在尝试序列化包含基本类型和派生类型列表的对象。下面给出了示例代码段。当列表仅包含基础对象时,序列化将正常工作。但是当我添加类型为'CompositeElement'的对象时,Serialize()调用会显示异常。

  

“ InvalidOperationException:类型SerializeTest.CompositeElement   没想到。使用XmlInclude或SoapInclude属性来   指定静态未知的类型。”

有什么方法可以序列化这样一个混合类型的列表?

private void Save(String path)
{
    ConfXML confXML = new ConfXML();
    confXML.ElementList = new List<Element>();

    // Add base element
    for (int i = 0; i < 3; i++)
        confXML.ElementList.Add(new Element(Type.Element, i.ToString()));

    // Add composite element
    CompositeElement compElement = new CompositeElement(Type.CompositeElement, "Composite", "Sensor1");
    confXML.ElementList.Add(compElement);

    XmlSerializer serializer = new XmlSerializer(typeof(ConfXML));
    using (TextWriter writer = new StreamWriter(path))
    {
        XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
        nameSpace.Add("", "");
        serializer.Serialize(writer, confXML, nameSpace);
    }
}

public enum Type
{
    Element,
    CompositeElement,
}

public class ConfXML
{
    private List<Element> elementList;

    [XmlElement("Elements")]
    public List<Element> ElementList
    {
        get { return elementList; }
        set { elementList = value; }
    }
}

public class Element
{
    private Type type;
    [XmlAttribute]
    public Type Type
    {
        get { return type; }
        set { type = value; }
    }


    private String name;
    [XmlAttribute]
    public String Name
    {
        get { return name; }
        set { name = value; }
    }

    public Element(Type typ, String nam)
    {
        this.Type = typ;
        this.Name = nam;
    }

    public Element()
    { }
}

public class CompositeElement : Element
{
    private String compData;
    [XmlAttribute]
    public String CompData
    {
        get { return compData; }
        set { compData = value; }
    }

    public CompositeElement(Type typ, String nam, String data) : base(typ, nam)
    {
        this.CompData = data;
    }

    public CompositeElement()
    {}
}

0 个答案:

没有答案