alielie
2025-05-12 7bf89fd93bc487e8445d6d85bb527251b7371a04
HMI.Core/Util/XmlHelper.cs
@@ -3,25 +3,32 @@
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using static System.Net.WebRequestMethods;
namespace HMI.Core.Util
{
    public static class XmlHelper
    {
        static readonly XmlSerializerNamespaces DEFAULT_NS = new XmlSerializerNamespaces();
        static XmlHelper()
        {
            DEFAULT_NS.Add("", "");
        }
        /// <summary>
        /// serialize object to xml file.
        /// </summary>
        /// <param name="path">the path to save the xml file</param>
        /// <param name="obj">the object you want to serialize</param>
        public static void SerializeToXml(string path, object obj)
        {
        {
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            string content = string.Empty;
            //serialize
            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, obj);
                serializer.Serialize(writer, obj, DEFAULT_NS);
                content = writer.ToString();
            }
            //save to file
@@ -45,13 +52,15 @@
                return (T)serializer.Deserialize(reader);
            }
        }
        public static bool ReadFromXml<T>(T obj, string path) {
        public static bool ReadFromXml<T>(T obj, string path)
        {
            XmlDocument xd = new XmlDocument();
            xd.Load(path);
            Type type = typeof(T);
            XmlNode root = xd.SelectSingleNode(type.Name);
            if (root == null) {
            if (root == null)
            {
                return false;
            }
@@ -70,5 +79,15 @@
            return true;
        }
        public static T DeepClone<T>(T data)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(stream, data);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)serializer.Deserialize(stream);
            }
        }
    }
}