C# XML文件序列化

C# XML文件序列化

XML文件序列化和反序列化

        /// 
        /// 读取XML文件反序列化指定类型
        /// 
        public object serializationReadXml(Type object_type, string path)
        {
     
            XmlSerializer serializer = new XmlSerializer(object_type);
            using (StreamReader reader = new StreamReader(path))
            {
     
                return serializer.Deserialize(reader);
            }
        }

        /// 
        /// 序列化对象并写入XML文件
        /// 
        public void serializationSaveXml(object obj, string path)
        {
     
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            string content = string.Empty;

            using (StringWriter writer = new StringWriter())
            {
     
                serializer.Serialize(writer, obj);
                content = writer.ToString();
            }

            using (StreamWriter streamWriter = new StreamWriter(path))
            {
     
                streamWriter.Write(content);
            }
        }

示例
建立对象结构,也可用类代替。

    public struct Items
    {
     
        public string Name {
      get; set; }
        public bool IsActive {
      get; set; }
        public double Item0 {
      get; set; }
        public double Item1 {
      get; set; }
        public double Item2 {
      get; set; }
        public double Item3 {
      get; set; }
        public double Item4 {
      get; set; }
    }

    public struct FItem
    {
     
        public string fileName {
      get; set; }
        public List<Items> Item {
      get; set; }
    }

结构对象写入MXL文件

        public void test()
        {
     
            List<Items> zItem = new List<Items>();
            string[] names = {
      "测试0", "测试1", "测试2", "测试3" };
            foreach (string name in names)
            {
     
                Items items = getItems(name);
                zItem.Add(items);
            }

            FItem fItem = new FItem();
            fItem.fileName = "name";
            fItem.Item = zItem;

            string path = @"D:\xml.xml";
            this.serializationSaveXml(fItem, path);
        }

        private Items getItems(string name)
        {
     
            Items items = new Items()
            {
     
                Name = name,
                IsActive = false,
                Item0 = 0,
                Item1 = 0,
                Item2 = 0,
                Item3 = 0,
                Item4 = 0,
            };
            return items;
        }

读XML文件反序列化,如果对象对不上则可能只读部分内容

        private void readXml()
        {
     
            string path = @"D:\xml.xml";
            FItem fItem = (FItem)this.serializationReadXml(typeof(FItem), path);
            Console.WriteLine($"name: {fItem.fileName}");
            Console.WriteLine($"测试0: {fItem.Item[0].Name}");
        }

你可能感兴趣的:(C#)