ningshuxia
2022-12-09 950a104d4690606f3b9744cc4b917b45fef34fb3
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
 
 
namespace IStation.Application
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class XmlHelper<T> where T : class
    {
        /// <summary>
        /// 对象生成Xml文档
        /// </summary>
        public string ObjectToXml(T obj)
        {
            using (StringWriter writer = new StringWriter())
            {
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(writer, obj);
                return writer.ToString();
            }
        }
 
 
        /// <summary>
        /// xml文档生成类
        /// </summary>
        public T XmlToObject(string xmlStr)
        {
            try
            {
                using (StringReader reader = new StringReader(xmlStr))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(reader) as T;
                }
            }
            catch (Exception ex)
            {
                var a = ex.Message;
                return null;
            }
        }
 
 
        /// <summary>
        /// 保存对象到xml文件中
        /// </summary>
        public static void SaveObjectXmlFile<T>(string fileName, T t) where T : class
        {
            var str = new XmlHelper<T>().ObjectToXml(t);
            File.WriteAllText(fileName, str, Encoding.UTF8);
        }
 
 
    }
}