C#序列化XML文件

C#序列化XML文件

本Markdown编辑器使用[StackEdit][6]修改而来,用它写博客,将会带来全新的体验哦:

  • 序列化类
  • 方法调用

序列化类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace Bnu.Coastal.SysManage
{
    public class Achieves
    {
        //序列化对象的集合
        public List imgFiles = new List();

        //正序列化:从对象到XML
        public void Serializer(string filename)
        {
            using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                XmlSerializer xs = new XmlSerializer(typeof(Achieves));
                xs.Serialize(fs, this);
            }
        }
        //反序列化:从XML到对象
        public static Achieves Deserialize(string filename)
        {
            Achieves aa = null;
             using (FileStream fs = new FileStream(filename, FileMode.Open))
            {
                XmlSerializer xs = new XmlSerializer(typeof(Achieves));
                aa = xs.Deserialize(fs) as Achieves;           
            }
            return aa;
        }       
    }
    //定义序列化对象
    public class ImgFile
    {
        public string fileId { get; set; }
        public string fileType { get; set; }
        public string fileName { get; set; }   
    }
}

正序列化

string xmlFile = "filePath";
List imgFileList = Achieves.Deserialize(xmlFile).imgFiles;

反序列化

string xmlFile = "filePath";
var ach = Achieves.Deserialize(xmlFile);
List imgFileList = ach.imgFiles;
ImgFile img = new ImgFile();
imgFileList.Add(img);
ach.Serializer(xmlFile);

你可能感兴趣的:(个人总结)