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 @   FredGrit  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
历史上的今天:
2022-12-13 cpp google unit test gtest
2021-12-13 C++ retrieve array via returned array pointer .Retrieve array via returned pointer one by one.
2019-12-13 Additional information: The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding elemen
点击右上角即可分享
微信分享提示