【问题标题】:How to serialize a class member to xml based on its type如何根据类型将类成员序列化为 xml
【发布时间】:2013-12-18 10:38:18
【问题描述】:

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

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>

有什么帮助吗?

【问题讨论】:

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


    【解决方案1】:

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

    1. Room 类必须实现接口“IXmlSerializable”。这将使您的序列化更加灵活 (How to Implement IXmlSerializable Correctly)。
    2. 或者您可以使用XmlAttributeOverrides 来覆盖序列化。 (Custom XML-element name for base class field in serialization)

    【讨论】:

    • 谢谢。我在您的链接中找到了这个想法。 public class Room { [XmlElement("Student", typeof(Student))] [XmlElement("Teacher", typeof(Teacher))] public List&lt;Person&gt; Persons { get; set; } }
    【解决方案2】:

    这是解决方案,但多了一个中间层。

    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; }
        }
    }
    

    【讨论】:

    • 谢谢,我之前试过这个,输出很好。但是有一个额外的&lt;Persons&gt; 元素。这就是我需要的: 001James
    猜你喜欢
    • 2023-03-03
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    相关资源
    最近更新 更多