C# xml, serialize List<T> to xml file and deserialize from xml file to List<T>

using System.Diagnostics;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApp9
{
    internal class Program
    {
        static string xmlFile = "testserializetoxml.xml";
        static void Main(string[] args)
        {
            Task.Run(() =>
            {
                MonitorMemoryCost();
            });

            //SerializeListTToXmlDemo();
            DeserializeXmlDemo(xmlFile);
        }

        static void DeserializeXmlDemo(string xmlFile)
        {
            var deserializedBooksList = DeserializeXmlToListT<Book>(xmlFile);
            if (deserializedBooksList != null && deserializedBooksList.Any())
            {
                Console.WriteLine($"Count:{deserializedBooksList.Count}");
            }
        }


        static List<T> DeserializeXmlToListT<T>(string xmlFile)
        {
            List<T> dataList = new List<T>();
            try
            {
                using (StreamReader reader = new StreamReader(xmlFile, System.Text.Encoding.UTF8))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
                    var tempList = serializer.Deserialize(reader) as List<T>;
                    if (tempList != null && tempList.Any())
                    {
                        dataList = new List<T>(tempList);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return dataList;
        }

        static void SerializeListTToXmlDemo()
        {
            List<Book> booksList = new List<Book>();
            InitData(ref booksList);
            SerializeListTToXml<Book>(booksList, xmlFile);
            Console.WriteLine($"SerializeListTToXmlDemo() done!");
        }

        static void SerializeListTToXml<T>(List<T> dataList,string xmlFileName)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.Encoding = System.Text.Encoding.UTF8;
                var xmlWriter = XmlWriter.Create(xmlFileName, settings);
                serializer.Serialize(xmlWriter, dataList); 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static void InitData(ref List<Book> booksList)
        {
            for (int i = 0; i < 10000000; i++)
            {
                booksList.Add(new Book()
                {
                    Id = i + 1,
                    ISBN = $"ISBN_{i + 1}_{Guid.NewGuid().ToString()}",
                    Name = $"Name_{i + 1}",
                    Title = $"Title_{i + 1}",
                    Topic = $"Topic_{i + 1}"
                });
            }
        }


        static void MonitorMemoryCost()
        {
            while (true)
            {
                var proc=Process.GetCurrentProcess();
                string costMemory = (proc.PrivateMemorySize64 / 1024 /1024).ToString("N0");
                Console.WriteLine($"{DateTime.UtcNow},Memory {costMemory} M");
                Thread.Sleep(1000);
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }

        public string ISBN { get; set; }

        public string Name { get; set; }

        public string Title { get; set; }

        public string Topic { get; set; }

    }
}

 

 

 

 

 

 

 

 

 

posted @ 2024-12-13 23:35  FredGrit  阅读(33)  评论(0)    收藏  举报