如何将列表保存到 XML 文件中
Posted
技术标签:
【中文标题】如何将列表保存到 XML 文件中【英文标题】:How to save a List into an XML file 【发布时间】:2013-09-27 16:00:43 【问题描述】:我有以下代码。其中我有一些东西保存到一个列表中,我希望将这两个列表保存在一个 XML 文件中,但是程序在尝试调试它时会在“51”行中断。
接下来的事情:
XmlSerializer xs = new XmlSerializer(typeof(T));
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
namespace Maman15cs
public class XSerial
/// <summary>
/// Save an instance of a class to an XML file
/// </summary>
/// <param name="filename">Full or relative path to the file</param>
/// <param name="cls">Class to serialize and save.</param>
/// <param name="t">Type of the class (use: typeof(ClassName)</param>
/// <returns>True on success, False on failure</returns>
public static void Save<T>(string filename, T cls)
using (Stream s = File.Open(filename, FileMode.Create))
using (StreamWriter sw = new StreamWriter(s))
sw.Write( SerializeObject<T>(cls) );
sw.Close();
s.Close();
return;
/// <summary>
/// Serialize the object into an XML format
/// </summary>
/// <typeparam name="T">Type of object to serialize</typeparam>
/// <param name="pObject">the object to serialize</param>
/// <returns>a string representing the XML version of the object</returns>
public static String SerializeObject<T>(T pObject)
MemoryStream memoryStream = new MemoryStream();
UTF8Encoding encoding = new UTF8Encoding();
XmlSerializer xs = new XmlSerializer(typeof(T));
System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, (object) pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
return encoding.GetString(memoryStream.ToArray());
/// <summary>
/// Deserialize the object back into the object from an XML string
/// </summary>
/// <typeparam name="T">Type of the object to restore</typeparam>
/// <param name="pXmlizedString">The string that represents the object in XML</param>
/// <returns>A new instance of the restored object</returns>
public static T DeserializeObject<T>(String pXmlizedString)
UTF8Encoding encoding = new UTF8Encoding();
XmlSerializer xs = new XmlSerializer(typeof(T));
MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(pXmlizedString));
System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(memoryStream, Encoding.UTF8);
return (T)xs.Deserialize(memoryStream);
public class ClassRoom
public string ClassNumber get; set;
public int NumberofPlaces get; set;
public string[,] DayandHour = new string[6, 8];
public static ClassRoom AddClassRoom()
var classRoom = new ClassRoom();
Console.WriteLine("Enter the Class number, the Number of places\n");
classRoom.ClassNumber = Console.ReadLine();
classRoom.NumberofPlaces = int.Parse(Console.ReadLine());
return classRoom;
public ClassRoom AddCourseInClas-s-room(ClassRoom clas-s-room, string courseNum)
for (int i = 0; i < 6; i++)
for (int j = 0; j < 8; j++)
if (String.IsNullOrEmpty(clas-s-room.DayandHour[i, j]))
clas-s-room.DayandHour[i, j] = courseNum;
return clas-s-room;
return null;
public void PrintClassRoom(ClassRoom clas-s-room)
for (int i = 0; i < 6; i++)
for (int j = 0; j < 8; j++)
if (!(String.IsNullOrEmpty(clas-s-room.DayandHour[i, j])))
Console.WriteLine(" 0", clas-s-room.DayandHour[i, j]);
Console.WriteLine("\n");
public void PrintList<T>(IEnumerable<T> col)
foreach (var item in col)
Console.WriteLine(item);
public void DeleteCourse(string coursenum, ClassRoom clas-s-room)
for (int i = 0; i < 6; i++)
for (int j = 0; j < 8; j++)
if (clas-s-room.DayandHour[i, j] == coursenum)
clas-s-room.DayandHour[i, j] = null;
public class Course
public string CourseName;
public string CourseNumber;
public int StudentsNumber;
public string TeacherName;
public string ClassNumber;
public static Course AddCourse()
Course newCourse = new Course();
Console.WriteLine("Enter the Course's name, course's number, students number, teacher's name, and class' number\n");
newCourse.CourseName = Console.ReadLine().ToString();
newCourse.CourseNumber = Console.ReadLine();
newCourse.StudentsNumber = int.Parse(Console.ReadLine());
newCourse.TeacherName = Console.ReadLine().ToString();
newCourse.ClassNumber = Console.ReadLine().ToString();
return newCourse;
public void PrintCourse(Course course)
Console.WriteLine("The course name is " + course.CourseName);
Console.WriteLine("\nThe course number is " + course.CourseNumber);
Console.WriteLine("\nThe class number is " + course.ClassNumber);
Console.WriteLine("\nThe students number is " + course.StudentsNumber);
Console.WriteLine("\nTeacher's name is " + course.TeacherName + "\n");
public class Program
static void Main(string[] args)
var course = new List<Course>();
var clas-s-room = new List<ClassRoom>();
bool loop = true;
int actionChoice;
while (loop == true)
Console.WriteLine("What do you want to do? (Enter number): \n 1)Add a new Course \n 2)Add a new class room \n 3)Add an existing course to an existing clas-s-room \n 4)Read the information of a specific clas-s-room \n 5)Read the information of all the clas-s-rooms \n 6)Read the information of a specific course \n 7)Delete a specific course in a specific clas-s-rom \n 8)Exit the program \n");
actionChoice = int.Parse(Console.ReadLine());
switch (actionChoice)
case 1: //Add a new Course
var new_course = Course.AddCourse();
course.Add(new_course);
break;
case 2:
var new_classRoom = ClassRoom.AddClassRoom();
clas-s-room.Add(new_classRoom);
break;
case 3:
Console.WriteLine("Enter the course's number and the clas-s-room's number");
var courseNumber = Console.ReadLine();
var clas-s-roomNumber = Console.ReadLine();
foreach (ClassRoom room in clas-s-room)
if (room.ClassNumber == clas-s-roomNumber)
room.AddCourseInClas-s-room(room, courseNumber);
foreach(Course _course in course)
if(_course.CourseNumber == courseNumber)
_course.ClassNumber = clas-s-roomNumber;
break;
case 4:
Console.WriteLine("Enter the clas-s-room number");
clas-s-roomNumber = Console.ReadLine();
foreach (ClassRoom room in clas-s-room)
if (room.ClassNumber == clas-s-roomNumber)
room.PrintClassRoom(room);
break;
case 5:
foreach (ClassRoom room in clas-s-room)
room.PrintClassRoom(room);
break;
case 6:
Console.WriteLine("Enter the course number");
courseNumber = Console.ReadLine();
foreach (Course ccourse in course)
if (ccourse.CourseName == courseNumber)
ccourse.PrintCourse(ccourse);
break;
case 7:
Console.WriteLine("Enter the course's number and the clas-s-room's num");
courseNumber = Console.ReadLine();
clas-s-roomNumber = Console.ReadLine();
foreach (ClassRoom classRoom in clas-s-room)
if (classRoom.ClassNumber == clas-s-roomNumber)
classRoom.DeleteCourse(courseNumber, classRoom);
break;
case 8:
loop = false;
break;
XSerial.Save("Course.xml", course);
XSerial.Save("Clas-s-room.xml", clas-s-room);
如果有人可以帮我完成这个,并纠正部分(我怀疑问题来自方法 SerializeObject)。
【问题讨论】:
System.Xml.dll 中出现“System.InvalidOperationException”类型的未处理异常附加信息:反映类型“System.Collections.Generic.List`1[Maman15cs.ClassRoom]”时出现错误. 【参考方案1】:你应该改变这一行
public string[,] DayandHour = new string[6, 8];
属于 ClassRoom
类,因为 Xml 序列化不支持多维数组。
【讨论】:
【参考方案2】:看看用于在运行时动态确定类型的反射 API。
typeof
与 GetType()
: Type Checking: typeof, GetType, or is?
反射API:http://msdn.microsoft.com/en-us/library/ms173183%28v=vs.90%29.aspx
【讨论】:
谢谢,我去查一下T.GetType()
不可编译。
T 是参数类型,在给定的上下文中无效
是的@LB 是对的。但是您需要在调用 XmlSerializer 方法之前确定对象的类型,因为您不能在运行时使用typeof
。如果你总是知道类是什么,尽管在这里没有理由使用泛型......以上是关于如何将列表保存到 XML 文件中的主要内容,如果未能解决你的问题,请参考以下文章
谁能帮我知道如何将 ags xmpp 联系人列表添加到 XML 文件并从中显示到列表视图中