如何根据类型将类成员序列化为xml

时间:2013-12-18 10:38:18

标签: c# xml serialization xml-serialization abstract-class

问题:我有一些可序列化的类:

public abstract class Person {}
public class Student : Person {}
public class Teacher : Person {}

[Serializable()]
[XmlIncludeAttribute(typeof(Student))]
[XmlIncludeAttribute(typeof(Teacher))]
public class Room
{   
    [XmlElementAttribute(??)]
    public Person[] persons;
}

假设我有一个这样的对象:

Room r = new Room();
r.persons= new Person[]{new Student(), new Teacher()};

我的结果:当我序列化它时,它将是这样的:

<Room>
    <Person />
    <Person />
</Room>

我需要什么:我需要的是这个,但我不知道

<Room>
    <Student/>
    <Teacher/>
</Room>

任何帮助?

2 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点,其中有两种:

  1. Room必须实现接口'IXmlSerializable'。这样您就可以更灵活地进行序列化(How to Implement IXmlSerializable Correctly)。
  2. 或者您可以使用XmlAttributeOverrides覆盖序列化。 (Custom XML-element name for base class field in serialization

答案 1 :(得分:1)

这是解决方案,但还有一个中间层。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication8 {
    class Program {
        static void Main(string[] args) {
            Room r = new Room();
            r.Persons = new List<Person>();
            r.Persons.Add(new Student() { StudentID = "001" });
            r.Persons.Add(new Teacher() { Name = "James" });

            var serializer = new XmlSerializer(typeof(Room));
            serializer.Serialize(Console.Out, r);

            Console.Read();
        }
    }

    public class Person { }

    public class Student : Person {
        public String StudentID { get; set; }
    }

    public class Teacher : Person {
        public String Name { get; set; }
    }

    public class Room {
        [XmlArrayItem(typeof(Student)),
        XmlArrayItem(typeof(Teacher))]
        public List<Person> Persons { get; set; }
    }
}