如何将List保存到XML文件中

时间:2013-09-27 16:00:43

标签: c# xml file list save

我有以下代码。我将一些内容保存到列表中,并希望将这两个列表保存在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 AddCourseInClassroom(ClassRoom classroom, string courseNum)
        {
            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    if (String.IsNullOrEmpty(classroom.DayandHour[i, j]))
                    {
                        classroom.DayandHour[i, j] = courseNum;
                        return classroom;
                    }
                }
            }
            return null;
        }

        public void PrintClassRoom(ClassRoom classroom)
        {
            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    if (!(String.IsNullOrEmpty(classroom.DayandHour[i, j])))
                    {
                        Console.WriteLine(" {0}", classroom.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 classroom)
        {
            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    if (classroom.DayandHour[i, j] == coursenum)
                    {

                        classroom.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 classroom = 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 classroom \n 4)Read the information of a specific classroom \n 5)Read the information of all the classrooms \n 6)Read the information of a specific course \n 7)Delete a specific course in a specific classrom \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();
                       classroom.Add(new_classRoom);
                       break;

                    case 3:
                        Console.WriteLine("Enter the course's number and the classroom's number");
                        var courseNumber = Console.ReadLine();
                        var classroomNumber = Console.ReadLine();

                        foreach (ClassRoom room in classroom)
                        {
                            if (room.ClassNumber == classroomNumber)

                                room.AddCourseInClassroom(room, courseNumber);
                        }

                        foreach(Course _course in course)
                        {
                            if(_course.CourseNumber == courseNumber)
                                _course.ClassNumber = classroomNumber;
                        }
                        break;

                    case 4:
                        Console.WriteLine("Enter the classroom number");
                        classroomNumber = Console.ReadLine();

                        foreach (ClassRoom room in classroom)
                        {
                            if (room.ClassNumber == classroomNumber)
                            {
                                room.PrintClassRoom(room);
                            }
                        }
                        break;

                    case 5:
                        foreach (ClassRoom room in classroom)
                        {
                            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 classroom's num");
                        courseNumber = Console.ReadLine();
                        classroomNumber = Console.ReadLine();

                        foreach (ClassRoom classRoom in classroom)
                        {
                            if (classRoom.ClassNumber == classroomNumber)
                                classRoom.DeleteCourse(courseNumber, classRoom);
                        }
                        break;

                    case 8:
                        loop = false;
                        break;
                }
            }

            XSerial.Save("Course.xml", course);
            XSerial.Save("Classroom.xml", classroom);
        }
    }
}

如果有人可以帮我完成这个,并更正部分(我怀疑问题来自SerializeObject方法)。

2 个答案:

答案 0 :(得分:1)

你应该改变这一行

public string[,] DayandHour = new string[6, 8];
ClassRoom

因为Xml序列化的多维数组不支持

答案 1 :(得分:-1)

查看Reflection API,它用于在运行时动态确定类型。

typeof vs GetType()Type Checking: typeof, GetType, or is?

Reflection API:http://msdn.microsoft.com/en-us/library/ms173183%28v=vs.90%29.aspx