songjun
2024-09-04 cc908053e0b5075fbfd27350b6da4b39bca9e550
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
 
namespace BatchService.Framework.Utility
{
    public class XMLHelper
    {
        public static T GetEntityFromFile<T>(string xmlFilePath) where T : new()
        {
            if (!File.Exists(xmlFilePath))
            {
                SaveEntityToFile<T>(new T(), xmlFilePath);
            }
            using (FileStream fs = new FileStream(xmlFilePath, FileMode.Open))
            {
                XmlSerializer xmlSerial = new XmlSerializer(typeof(T));
                return (T)xmlSerial.Deserialize(fs);
            }
        }
 
        public static void SaveEntityToFile<T>(T entity, string xmlFilePath)
        {
            if (File.Exists(xmlFilePath))
            {
                File.Delete(xmlFilePath);
            }
            XmlSerializer xmlSerial = new XmlSerializer(typeof(T));
            using (FileStream fs = new FileStream(xmlFilePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                xmlSerial.Serialize(fs, entity);
            }
        }
 
        public static string GetXMLNodeInnerText(XmlDocument xmlDoc, string xPath)
        {
            var xmlNode = xmlDoc.SelectSingleNode(xPath);
            if (xmlNode == null)
            {
                return "";
            }
            else
            {
                return xmlNode.InnerText;
            }
        }
    }
}