c# xmlelement在派生类中更改顺序
本文关键字:顺序 xmlelement 派生 | 更新日期: 2023-09-27 18:18:08
我正在尝试序列化XML。我想在派生类中添加一个新属性,并将其放在基类的其他属性之间。
在这个示例中,我想把'SpecialInterests'放在基类的'Name'和'Age'之间。
XML<!-- 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>
c# - Main(创建实例和序列化)
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; }
}
这个问题和另一个问题本质上是一样的。这里有一个很好的解释为什么这种序列化行为是这样的,以及一些处理它的方法。
。. NET序列化排序