如何使用 xml 属性序列化 属性 属性 而不是整个 属性?

how to serialize a property property only not the whole property using xml attributes?

我想序列化一个包含属性的对象,而其中一个属性我只想序列化它的名称。

如何在不实现 IXmlSerializable 接口,仅使用属性的情况下做到这一点。

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

    [XmlAttribute]
    public string ClassId{get;set;}

    [XmlAttribute]
    public Teacher Teacher{get;set;}

    [XmlArray("Students")]
    [XmlArrayItem("Student", Type=typeof(Student))]
    public List<Student> Students { get; } = new List<Student>();
}


[Serializable]
public class Student 
{
    public Student()
    {

    }

    public Class CurrentClass{get;set;}


    [XmlAttribute]
    public string Name { get; set; } = "New Student";

    [XmlAttribute]
    public int Age { get; set; } = 10;

}

CurrentClass这个属性不想理会

我只想序列化它的 CurrentClass.ClassId 值。

如果您只是寻找要与 Student 对象序列化的 ClassId,那么只有一个 ClassId 属性 而不是整个 Class对象。

public class GenerateXml
{
        public static void Create()
        {
            Class c = new Class();
            c.Teacher = new Teacher() {Name = "Mr. Henry"};
            var s = new Student() { Age = 14, Name = "Suzy", Teacher = c.Teacher };
            c.Students.Add(s);
            s = new Student() {Age = 13, Name = "Adam", Teacher = c.Teacher};
            c.Students.Add(s);

            var serializer = new XmlSerializer(c.GetType());
            XmlTextWriter writer = new XmlTextWriter("class.xml", Encoding.ASCII);
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 4;
            serializer.Serialize(writer, c);
        }
}

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

    [XmlAttribute]
    public string ClassId { get; set; }

    [XmlElement]
    public Teacher Teacher { get; set; }

    [XmlArray("Students")]
    [XmlArrayItem("Student", Type = typeof(Student))]
    public List<Student> Students { get; } = new List<Student>();
}


[Serializable]
public class Student
{
    public Student()
    {

    }

    [XmlElement]
    public Teacher Teacher { get; set; }

    [XmlAttribute]
    public string ClassId { get; set; }

    [XmlAttribute]
    public string Name { get; set; } = "New Student";

    [XmlAttribute]
    public int Age { get; set; } = 10;

}

[Serializable]
public class Teacher
{
    public Teacher()
    {

    }

    [XmlAttribute]
    public string Name { get; set; } = "New Teacher";

    [XmlAttribute]
    public int Age { get; set; } = 30;

}