我有两个类,如下所示,我想将对象学生序列化为a.xml文件。我可以创建xml文件,但不能使用' ClassName'属性。
[Serializable]
public class Person
{
[XmlAttribute]
public string FirstName { get; set; }
[XmlAttribute]
public string LastName { get; set; }
}
public class Student : System.Collections.CollectionBase, IEnumerable<Person>
{
[XmlAttribute]
public string ClassName { get; set; }
public void Add(Person person)
{
List.Add(person);
}
public Person this[int index]
{
get
{
return (Person)List[index];
}
}
#region IEnumerable<Person> 成员
public new IEnumerator<Person> GetEnumerator()
{
foreach (Person transducer in List)
yield return transducer;
}
#endregion
}
我得到了像这样的xml内容,没有ClassName字段
Student student = new Student();
student.Add(new Person(){ FirstName = "bill", LastName = "gates" });
student.Add(new Person(){ FirstName = "bill", LastName = "gates" });
student.ClassName = "AAA";
XmlSerializer x2 = new XmlSerializer(typeof(Student));
x2.Serialize(File.Create("ab.xml"), student);
我如何获得属性???
答案 0 :(得分:1)
问题在于对实现IList
的所有内容的默认序列化。它只列举内容,而不是属性。
对此的解决方案是不在序列化类中实现CollectionBase
,而是创建具有以下内容的属性:
public class Student
{
List<Person> Items { get; set; }
}