c# – List的XML序列化

前端之家收集整理的这篇文章主要介绍了c# – List的XML序列化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法使用 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()
    {
    }
........

解决方法

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

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

[XmlInclude(typeof(Cat))]
[XmlInclude(typeof(Dog))]
[XmlRoot(ElementName="Animal")]
public abstract class Animal : IAnimal
原文链接:https://www.f2er.com/csharp/96728.html

猜你在找的C#相关文章