欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# 读写XML文件(XML Helper)

程序员文章站 2022-06-10 18:07:06
...

在项目中哪个类只要using XmlManager类的Mynamespace就可以XmlManager.Instance.LoadXml<UserClass>(fullPath)调用。

 XML读写类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.ComponentModel;
using System.Reflection;
using System.IO;
using System.Dynamic;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;

namespace Mynamespace
{
    public class XmlManager : Singleton<XmlManager>
    {
        public void SaveXml<T>(T obj, String path) 
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            using (StreamWriter writer = new StreamWriter(path))
            {
                serializer.Serialize(writer, obj, ns);
            }
        }

        public T LoadXml<T>(String path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            try
            {
                using (StreamReader reader = new StreamReader(path))
                {
                    if (reader == null)
                        return default(T);

                    T obj = (T)serializer.Deserialize(reader);
                    reader.Close();

                    return obj;
                }
            }
            catch
            {
                return default(T);
            }
        }
    }
}

 Singleton类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mynamespace
{
    public class Singleton<T> where T : class, new()
    {
        private static object _syncobj = new object();
        private static volatile T _instance = null;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncobj)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                        }
                    }
                }
                return _instance;
            }
        }
    }
}