XmlSerializer自定义序列化

时间:2011-11-08 17:09:47

标签: .net xml

我有两个第一类继承自另一个。

例如Animal这是一个基类而Dog这是一个继承的类。

我填充了一个List集合,我想将它序列化为List Collection。

有可能吗?

string serializedResult = XmlSerializeHelper<List<Animal>>.Serialize(result.ToList());

Where result is a List<Dog> collection.

XmlSerializeHelper实现如下:

public class XmlSerializeHelper<T> where T : class
{
    public static string Serialize(object o)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringWriter stringWriter = new StringWriter();
        xmlSerializer.Serialize(stringWriter, o);
        return stringWriter.ToString();
    }
    public static T Deserialize(string xml)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringReader stringReader = new StringReader(xml);
        return (T)xmlSerializer.Deserialize(stringReader);
    }
}

1 个答案:

答案 0 :(得分:0)

如果你有一个列表(我通常使用数组列表),为所有派生类添加xml属性

    [XmlArray("Animal"),
     XmlArrayItem("Dog", typeof(Dog)),
     XmlArrayItem("Cat", typeof(Cat))]
    public ArrayList Animals = new ArrayList();

这告诉序列化程序可以期待哪些类型......

... ...编辑 为了使其更具可读性,请考虑以下事项:

[Serializable]
public class ListOfAnimals
{
    public ListOfAnimals(){}

    [XmlArray("Animal"),
     XmlArrayItem("Dog", typeof(Dog)),
     XmlArrayItem("Cat", typeof(Cat))]
    public ArrayList Animals = new ArrayList();
}

[Serializable]
public class Animal
    {
        public Animal(){}

        public Animal(string name)
        {
            Name = name;
        }
        public string Name{ get;set;}
}

[Serializable]
public class Dog : Animal
{
    public Dog(){}

    public bool Vaccinated{ get;set; }
}

[Serializable]
public class Cat : Animal
{
    public Cat(){}

    public bool Neutered{ get;set; }
}

然后像这样调用序列化:

ListOfAnimals result = new ListOfAnimals();

Dog puppy1 = new Dog();
Dog puppy2 = new Dog();
Cat kitty1 = new Cat();
Cat kitty2 = new Cat();

puppy1.Name = "Lassie";
puppy2.Name = "Yeller";
kitty1.Name = "Miauu";
kitty2.Name = "Scratchy";

result.Animals.Add(puppy1);
result.Animals.Add(puppy2);
result.Animals.Add(kitty1);
result.Animals.Add(kitty2);

string serializedResult = XmlSerializeHelper<ListOfAnimals>.Serialize(result);