List <object> </object>的XML序列化

时间:2013-10-23 09:04:28

标签: c# xml list serialization

我无法使用XML序列化将动物列表保存到磁盘。

我收到Exception:Thrown:“不期望使用AnimalLibrary.Animals.Mammals.Dog类型。使用XmlInclude或SoapInclude属性指定静态未知的类型。” (System.InvalidOperationException)

如果我使用“Dog”尝试注释代码,它将按预期工作,并生成XML。但是作为列表中唯一元素发送的同一只狗不起作用。

    [XmlElement("animalList")]
    public List<Animal> animalList = new List<Animal>();

public bool SaveBinary(string fileName)
    {
        Mammals.Dog dog = (Mammals.Dog)animalList[0];

        //IObjectSerializer<Mammals.Dog> obj = new XMLObjectSerializer<Mammals.Dog>();
        IObjectSerializer<List<Animal>> obj = new XMLObjectSerializer<List<Animal>>();

        bool saved = obj.SaveFile(fileName, animalList);
        if (saved)
            return true;

        return false;
    }

XML序列化程序

public bool SaveFile(string fileName, T objectToSerialize)
    {
        try
        {
            //Will overwrite old file
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));

            StreamWriter myWriter = new StreamWriter(fileName);
            mySerializer.Serialize(myWriter, objectToSerialize);
            myWriter.Close();
        }
        catch (IOException ex)
        {
            Console.WriteLine("IO Exception ", ex.Message);
            return false;
        }
        return true;
    }

继承狗的文件。类中没有xml标签。

[XmlRoot(ElementName="Animal")]
public abstract class Animal : IAnimal
{

    /// <summary>
    /// Id of animal
    /// </summary>
    private string id;
    public string ID

........

[XmlRoot(ElementName = "Animals")]
public abstract class Mammal : Animal
{


   public int NumberofTeeth { get; set; }

........

[XmlRoot(ElementName="Dog")]
public class Dog : Mammal
{

    /// <summary>
    /// Constructor - Create an instance of a Dog
    /// </summary>
    public Dog()
    {
    }
........

1 个答案:

答案 0 :(得分:12)

如果您想要一个对象列表并将它们序列化为基类型列表,那么您需要告诉序列化器可以使用哪种具体类型。

因此,如果您想将Dog和Cat对象放入Animal列表,则需要将标记添加到Animal类中,如下所示

[XmlInclude(typeof(Cat))]
[XmlInclude(typeof(Dog))]
[XmlRoot(ElementName="Animal")]
public abstract class Animal : IAnimal