chr
2024-03-07 40213047b1cee48144c5a1eee1778ada6f609ca1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
using System.IO;
using System.Xml.Serialization;
 
namespace WPFProject.Utils
{
    public class XmlUtil
    {
        /// <summary>
        /// 将对象序列化到Xml文件中
        /// </summary>
        /// <param name="data">对象</param>
        /// <param name="filePath">xml路径</param>
        public static void SerialToFile(object data, string filePath)
        {
            XmlSerializer serializer = new XmlSerializer(data.GetType());
            string content = string.Empty;
            //serialize
            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, data);
                content = writer.ToString();
            }
            //save to file
            using (StreamWriter stream_writer = new StreamWriter(filePath))
            {
                stream_writer.Write(content);
            }
        }
 
        public static T DeserialFromXml<T>(string filePath)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StreamReader reader = new StreamReader(filePath))
            {
                return (T) serializer.Deserialize(reader);
            }
        }
 
    }
}