我正在尝试序列化XML。我想在派生类中添加一个新属性,并将其放在基类的其他属性之间。
在示例中,我想将'SpecialInterests'放在基类的'Name'和'Age'之间。
<!-- Output -->
<PersonenListe xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<PersonenArray>
<PersonObjekt>
<Name>Max Man</Name>
<Age>33</Age>
</PersonObjekt>
<PersonObjekt xsi:type="SpecialPerson">
<Name>Albert Einstein</Name>
<Age>36</Age>
<SpecialInterests>Physics</SpecialInterests>
</PersonObjekt>
</PersonenArray>
</PersonenListe>
<!-- Desire -->
<PersonenListe>
<PersonenArray>
<PersonObjekt>
<Name>Max Man</Name>
<Age>33</Age>
</PersonObjekt>
<PersonObjekt xsi:type="SpecialPerson">
<Name>Albert Einstein</Name>
<SpecialInterests>Physics</SpecialInterests>
<Age>36</Age>
</PersonObjekt>
</PersonenArray>
</PersonenListe>
static void Main(string[] args)
{
PersonalList personen = new PersonalList();
Person normPerson = new Person { Name = "Max Man", Age = 33 };
SpecialPerson specPerson = new SpecialPerson
{ Name = "Albert Einstein", Interests = "Physics", Age = 36 };
personen.AddPerson(normPerson);
personen.AddPerson(specPerson);
Type[] personTypes = new Type[personen.Persons.Count];
for (int i = 0; i < personen.Persons.Count; i++)
{
personTypes[i] = personen.Persons[i].GetType();
}
XmlSerializer serializer = new XmlSerializer(typeof(PersonalList), personTypes);
FileStream fs = new FileStream("Personenliste.xml", FileMode.Create);
serializer.Serialize(fs, personen);
fs.Close();
personen = null;
// Deserialize
fs = new FileStream("Personenliste.xml", FileMode.Open);
personen = (PersonalList)serializer.Deserialize(fs);
serializer.Serialize(Console.Out, personen);
Console.ReadLine();
}
[XmlRoot("PersonenListe")]
[XmlInclude(typeof(Person))]
public class PersonalList
{
[XmlArray("PersonenArray")]
[XmlArrayItem("PersonObjekt")]
public List<Person> Persons = new List<Person>();
public void AddPerson(Person person)
{
Persons.Add(person);
}
}
[XmlType("Person")]
public class Person
{
[XmlElement(ElementName = "Name", Order = 1)]
public virtual string Name { get; set; }
[XmlElement(ElementName = "Age", Order = 3)]
public virtual int Age { get; set; }
}
[XmlType("SpecialPerson")]
public class SpecialPerson : Person
{
[XmlElement(ElementName = "Name", Order = 1)]
public override string Name { get; set; }
[XmlElement(ElementName = "SpecialInterests", Order = 2)]
public string Interests { get; set; }
[XmlElement(ElementName = "Age", Order = 3)]
public override int Age { get; set; }
}