简体   繁体   中英

Serializing multiple List<T> objects in to the same XML file C#

Hello everyone I have three lists containing objects from the same class. For example, here are my lists:

    List<Course> courselvl4 = new List<Course>();
    List<Course> courselvl5 = new List<Course>();
    List<Course> courselvl6 = new List<Course>();

I was wondering if it is possible, to serialize each of these lists in to the same XML file and deserialize back in to the lists. Thanks. I have tried looking for the answer, but can not find it anywhere. Please direct if answered already.

You can go for this if you want to initialize your list with the proper capacity:

Int32 capacity = courselvl4.Count + courselvl5.Count + courselvl6.Count;

List<Course> courses = new List<Course>(capacity);
courses.AddRange(courselvl4);
courses.AddRange(courselvl5);
courses.AddRange(courselvl6);

Alternatively:

List<Course> courses = courselvl4
                 .Concat(courselvl5)
                 .Concat(courselvl6)
                 .ToList();

Then just go for:

SerializeCourses("CoursesList",courses);

private static XDocument SerializeCourses(String rootElement, List<Course> courses)
{
    XDocument doc = new XDocument();

    using (XmlWriter writer = doc.CreateWriter())
    {
        writer.WriteStartElement(rootElement);

        foreach (Course course in courses)
            new XmlSerializer(typeof(Course)).Serialize(writer, course);

        writer.WriteEndElement();
    }

    return doc;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM