增加Prism 框架

This commit is contained in:
chfei committed 2026-08-31 16:28:23 +08:00
1 parent 2cd6b8db86
commit 726eb6de16
99 files changed
+12527

No files matched your search

@@ -0,0 +1,156 @@
using MAX.Framework.Commons;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
namespace MAX.Framework.Helpers
{
/// <summary>
/// App 配置
/// </summary>
public class AppConfigHelper
{
public static string exeConfigPath = Assembly.GetEntryAssembly()?.Location ?? "";
public static string GetConnectionString(string name)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
string connection = config.ConnectionStrings.ConnectionStrings[name].ConnectionString ?? "";
//string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
return connection;
}
///<summary>
///返回*.exe.config文件中appSettings配置节的value项
///</summary>
///<param name="strKey"></param>
///<returns></returns>
public static TValue GetAppConfig<TValue>(string strKey, TValue def = default)
{
try
{
string value = GetAppConfig(strKey);
return MAX.Core.Helpers.Convert.To<TValue>(value);
}
catch (Exception ex)
{
return def;
}
}
///<summary>
///返回*.exe.config文件中appSettings配置节的value项
///</summary>
///<param name="strKey"></param>
///<returns></returns>
public static string GetAppConfig(string strKey)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
foreach (string key in config.AppSettings.Settings.AllKeys)
{
if (key == strKey)
{
return config.AppSettings.Settings[strKey].Value.ToString();
}
}
return null;
}
public static List<KeyValue> GetAppSettings()
{
Configuration config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
List<KeyValue> settings = new List<KeyValue>();
foreach (string key in config.AppSettings.Settings.AllKeys)
{
settings.Add(new KeyValue(key, config.AppSettings.Settings[key].Value));
}
return settings;
}
///<summary>
///在*.exe.config文件中appSettings配置节增加一对键值对
///</summary>
///<param name="newKey"></param>
///<param name="newValue"></param>
public static void UpdateAppConfig(string newKey, string newValue)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
bool exist = false;
foreach (string key in config.AppSettings.Settings.AllKeys)
{
if (key == newKey)
{
exist = true;
}
}
if (exist)
{
config.AppSettings.Settings.Remove(newKey);
}
config.AppSettings.Settings.Add(newKey, newValue);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
/// <summary>
/// 静态类型写入配置文件信息
/// 名称相同
/// </summary>
/// <param name="appType"></param>
public static void SetAppConfig(Type appType)
{
PropertyInfo[] props = appType.GetProperties(BindingFlags.Static | BindingFlags.Public);
List<KeyValue> settings = GetAppSettings();
foreach (KeyValue item in settings)
{
try
{
PropertyInfo prop = props.FirstOrDefault(a => a.Name.ToLower() == item.Key.ToLower());
if (prop != null)
{
object value = Core.Helpers.Convert.To(prop.PropertyType, item.Value);
prop.SetValue(null, value);
}
}
finally
{
}
}
}
/// <summary>
/// 静态配置文件信息写入到配置文件中
/// 只写入配置文件中存在的配置项中
/// </summary>
/// <param name="appType"></param>
public static void UpdateAppConfig(Type appType)
{
PropertyInfo[] props = appType.GetProperties(BindingFlags.Static | BindingFlags.Public);
List<KeyValue> settings = GetAppSettings();
foreach (KeyValue item in settings)
{
try
{
PropertyInfo prop = props.FirstOrDefault(a => a.Name.ToLower() == item.Key.ToLower());
if (prop != null)
{
object value = prop.GetValue(null);
if (value?.ToString().ToLower() == item.Value.ToLower())
{
continue;
}
UpdateAppConfig(item.Key, value?.ToString());
}
}
finally
{
}
}
}
}
}
@@ -0,0 +1,74 @@
using MAX.Core.DependencyInjection;
using MAX.Framework.Configs;
using MAX.Framework.Interfaces;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;
namespace MAX.Framework.Helpers
{
/// <summary>
/// 配置
/// </summary>
public class ConfigHelper
{
private static IFolderConfig _folderConfig = LazyServiceProvider.Instance.LazyGetService<IFolderConfig>();
public static string prvategp = "4Z-zy_VP";//pIuEFX-0-OZm%tP2qtKw
public static T LoadConfig<T>() where T : ConfigBase
{
string filename = Activator.CreateInstance<T>().ConfigName;
return LoadConfig<T>(filename);
}
public static T LoadConfig<T>(string fileName) where T : ConfigBase
{
try
{
string filePath = GetConfigUserPath(fileName);
if (File.Exists(filePath))
{
string content = File.ReadAllText(filePath, Encoding.UTF8);
return JsonConvert.DeserializeObject<T>(content);
}
}
catch { }
return default;
}
public static void SaveConfig<T>(T config) where T : ConfigBase
{
string filename = Activator.CreateInstance<T>().ConfigName;
SaveConfig(filename, config);
}
public static void SaveConfig<T>(string fileName, T config) where T : ConfigBase
{
try
{
string filePath = GetConfigUserPath(fileName);
FileHelper.CreateDirectory(filePath);
string content = JsonConvert.SerializeObject(config);
File.WriteAllText(filePath, content, Encoding.UTF8);
}
catch { }
}
public static void SaveConfig(string fileName, string content)
{
try
{
string filePath = GetConfigUserPath(fileName);
FileHelper.CreateDirectory(filePath);
File.WriteAllText(filePath, content, Encoding.UTF8);
}
catch { }
}
public static string GetConfigUserPath(string fileName)
{
string filePath = Path.Combine(_folderConfig.LocalAppFolder, "config", fileName);
return filePath;
}
}
}
+181
View File
@@ -0,0 +1,181 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace MAX.Framework.Helpers
{
/// <summary>
/// 文件操作帮助类
/// </summary>
public class FileHelper
{
/// <summary>
/// 获取文件MD5值
/// </summary>
/// <param name="FilePath"></param>
/// <returns></returns>
public static string GetFileMd5(string FilePath)
{
try
{
FileStream get_file = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hash_byte = get_md5.ComputeHash(get_file);
string resule = BitConverter.ToString(hash_byte);
resule = resule.Replace("-", "");
get_file.Close();
return resule;
}
catch (Exception e)
{
return e.ToString();
}
}
/// <summary>
/// 读取所有内容 相对路径Or绝对路径
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static string ReadAllText(string file)
{
if (!Path.IsPathRooted(file))
{
file = Path.Combine(GlobalConfig.AppDirectory, file);
}
if (File.Exists(file))
{
return _ReadAllText(file, Encoding.UTF8);
}
return string.Empty;
}
/// <summary>
/// 读取所有内容 绝对路径
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static string ReadAbsAllText(string file)
{
return _ReadAllText(file, Encoding.UTF8);
}
/// <summary>
/// 读取所有内容 相对路径
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static string ReadPartialAllText(string file)
{
string _file = Path.Combine(GlobalConfig.AppDirectory, file);
return _ReadAllText(_file, Encoding.UTF8);
}
private static string _ReadAllText(string file, Encoding encoding)
{
if (File.Exists(file))
{
return File.ReadAllText(file, encoding);
}
else
{
throw new Exception($"缺失文件{file}");
}
}
/// <summary>
/// 创建目录
/// </summary>
/// <param name="dir"></param>
public static void CreateDirectory(string dir)
{
if (Path.HasExtension(dir))
{
dir = Path.GetDirectoryName(dir);
}
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
public static bool DeleteDirectory(string path)
{
try
{
Directory.Delete(path, true);
return true;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
return false;
}
}
public static void CopyDirectory(string sourceDir, string destinationDir, bool recursive = true)
{
// Get information about the source directory
DirectoryInfo dir = new DirectoryInfo(sourceDir);
// Check if the source directory exists
if (!dir.Exists)
{
throw new DirectoryNotFoundException($"Source directory not found: {dir.FullName}");
}
// Cache directories before we start copying
DirectoryInfo[] dirs = dir.GetDirectories();
// Create the destination directory
Directory.CreateDirectory(destinationDir);
// Get the files in the source directory and copy to the destination directory
foreach (FileInfo file in dir.GetFiles())
{
string targetFilePath = Path.Combine(destinationDir, file.Name);
file.CopyTo(targetFilePath);
}
// If recursive and copying subdirectories, recursively call this method
if (recursive)
{
foreach (DirectoryInfo subDir in dirs)
{
string newDestinationDir = Path.Combine(destinationDir, subDir.Name);
CopyDirectory(subDir.FullName, newDestinationDir, true);
}
}
}
/// <summary>
/// 获取文件夹大小
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static long GetDirectorySize(string path)
{
long result = 0;
try
{
if (Directory.Exists(path))
{
dynamic fso = Activator.CreateInstance(Type.GetTypeFromProgID("Scripting.FileSystemObject"));
dynamic fldr = fso.GetFolder(path);
result = (long)fldr.size;
}
else
{
result = 0;
}
}
catch (Exception ex)
{
result = 0;
}
return result;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,77 @@
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace MAX.Framework.Helpers
{
public static class ObjectHelper
{
private static readonly ConcurrentDictionary<string, PropertyInfo> CachedObjectProperties =
new ConcurrentDictionary<string, PropertyInfo>();
public static void TrySetProperty<TObject, TValue>(
TObject obj,
Expression<Func<TObject, TValue>> propertySelector,
Func<TValue> valueFactory,
params Type[] ignoreAttributeTypes
)
{
TrySetProperty(obj, propertySelector, x => valueFactory(), ignoreAttributeTypes);
}
public static void TrySetProperty<TObject, TValue>(
TObject obj,
Expression<Func<TObject, TValue>> propertySelector,
Func<TObject, TValue> valueFactory,
params Type[] ignoreAttributeTypes
)
{
string cacheKey =
$"{obj?.GetType().FullName}-"
+ $"{propertySelector}-"
+ $"{(ignoreAttributeTypes != null ? "-" + string.Join("-", ignoreAttributeTypes.Select(x => x.FullName)) : "")}";
PropertyInfo property = CachedObjectProperties.GetOrAdd(
cacheKey,
(name) =>
{
if (propertySelector.Body.NodeType != ExpressionType.MemberAccess)
{
return null;
}
MemberExpression memberExpression = (MemberExpression)propertySelector.Body;
PropertyInfo propertyInfo = obj?.GetType()
.GetProperties()
.FirstOrDefault(
x =>
x.Name == memberExpression.Member.Name
&& x.GetSetMethod(true) != null
);
if (propertyInfo == null)
{
return null;
}
if (
ignoreAttributeTypes != null
&& ignoreAttributeTypes.Any(
ignoreAttribute => propertyInfo.IsDefined(ignoreAttribute, true)
)
)
{
return null;
}
return propertyInfo;
}
);
property?.SetValue(obj, valueFactory(obj));
}
}
}
@@ -0,0 +1,144 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MAX.Framework.Helpers;
public class StringTypeHelper
{
public static object ConvertToObject(string input, out Type type)
{
type = typeof(string);
object value = input;
// 1. 检查布尔值(支持多种表示形式)
if (IsBoolean(input, out bool boolValue))
{
type = typeof(bool);
value = boolValue;
return value;
}
// 2. 检查整数
if (int.TryParse(input, NumberStyles.Integer, CultureInfo.InvariantCulture, out int intValue))
{
type = typeof(int);
value = intValue;
return value;
}
// 3. 检查无符号整数
if (ulong.TryParse(input, NumberStyles.Integer, CultureInfo.InvariantCulture, out ulong ulongValue))
{
type = typeof(ulong);
value = ulongValue;
return value;
}
// 4. 检查双精度浮点数
if (double.TryParse(input, NumberStyles.Number | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
CultureInfo.InvariantCulture, out double doubleValue))
{
type = typeof(double);
value = doubleValue;
return value;
}
// 5. 检查十进制数
if (decimal.TryParse(input, NumberStyles.Number | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
CultureInfo.InvariantCulture, out decimal decimalValue))
{
type = typeof(decimal);
value = decimalValue;
return value;
}
// 6. 检查日期时间
if (IsDateTime(input, out DateTime dateTimeValue))
{
type = typeof(DateTime);
value = dateTimeValue;
return value;
}
// 7. 检查null
if (input == null)
{
type = typeof(string);
value = null;
return value;
}
// 8. 默认返回字符串类型
type = typeof(string);
return value;
}
private static bool IsBoolean(string input, out bool boolValue)
{
boolValue = false;
// 支持多种布尔值表示形式
if (input.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase) ||
input.Equals(bool.FalseString, StringComparison.OrdinalIgnoreCase) ||
input.Equals("t", StringComparison.OrdinalIgnoreCase) ||
input.Equals("f", StringComparison.OrdinalIgnoreCase) ||
input.Equals("1", StringComparison.Ordinal) ||
input.Equals("0", StringComparison.Ordinal) ||
input.Equals("yes", StringComparison.OrdinalIgnoreCase) ||
input.Equals("no", StringComparison.OrdinalIgnoreCase) ||
input.Equals("真", StringComparison.Ordinal) ||
input.Equals("假", StringComparison.Ordinal))
{
boolValue = input.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase) ||
input.Equals("t", StringComparison.OrdinalIgnoreCase) ||
input.Equals("1", StringComparison.Ordinal) ||
input.Equals("yes", StringComparison.OrdinalIgnoreCase) ||
input.Equals("真", StringComparison.Ordinal);
return true;
}
return false;
}
private static bool IsDateTime(string input, out DateTime dateTimeValue)
{
dateTimeValue = default;
// 首先尝试使用默认的DateTime.TryParse进行解析
if (DateTime.TryParse(input, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateTime))
{
dateTimeValue = dateTime;
return true;
}
// 如果解析失败,尝试使用不同的格式字符串进行解析
string[] formats = {
"yyyy-MM-dd",
"yyyy/MM/dd",
"yyyy.MM.dd",
"yyyyMMdd",
"yyyy-MM-dd HH:mm",
"yyyy/MM/dd HH:mm",
"yyyy.MM.dd HH:mm",
"yyyy-MM-dd HH:mm:ss",
"yyyy/MM/dd HH:mm:ss",
"yyyy.MM.dd HH:mm:ss",
"yyyy-MM-dd HH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ss.fffK" // 支持ISO 8601格式带时区
};
// 使用TryParseExact尝试解析,提供多种格式字符串
foreach (string format in formats)
{
if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
dateTimeValue = dateTime;
return true;
}
}
return false;
}
}
@@ -0,0 +1,157 @@
using MAX.Core.Commons;
using System;
using System.Diagnostics;
using System.Text;
namespace MAX.Framework.Helpers
{
public class WinCmdHelper
{
#region 执行Dos命令
/// <summary>
/// 执行Dos命令
/// </summary>
/// <param name="cmd">Dos命令及参数</param>
/// <param name="isShowCmdWindow">是否显示cmd窗口</param>
/// <param name="isCloseCmdProcess">执行完毕后是否关闭cmd进程</param>
/// <returns>成功返回true,失败返回false</returns>
public static Result ExcuteDosCommand(string cmd, string workdir, bool isShowCmdWindow = false, bool isWaitForExit = false, bool isCloseCmdProcess = true)
{
Result result = new Result();
try
{
StringBuilder errString = new StringBuilder();
StringBuilder outString = new StringBuilder();
Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.WorkingDirectory = workdir;
p.StartInfo.Arguments = "/c " + cmd;
p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
p.StartInfo.StandardErrorEncoding = Encoding.UTF8;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = !isShowCmdWindow;
p.OutputDataReceived += new DataReceivedEventHandler(delegate (object sender, DataReceivedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Data))
{
outString.AppendLine(e.Data);
Debug.WriteLine(e.Data);
}
});
p.ErrorDataReceived += new DataReceivedEventHandler(delegate (object sender, DataReceivedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Data))
{
errString.AppendLine(e.Data);
}
});
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
if (isWaitForExit)
{
p.WaitForExit();
}
if (isCloseCmdProcess)
{
p.Close();
}
if (errString.Length <= 0)
{
result.Success = true;
result.Data = outString.ToString();
}
Console.WriteLine(string.Format("成功执行Dos命令[{0}]!", cmd));
return result;
}
catch (Exception ex)
{
Console.WriteLine("执行命令失败,请检查输入的命令是否正确:" + ex.Message, ex);
result.Msg = ex.Message;
}
return result;
}
private static void P_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
throw new NotImplementedException();
}
#endregion
#region 判断指定的进程是否在运行中
/// <summary>
/// 判断指定的进程是否在运行中
/// </summary>
/// <param name="processName">要判断的进程名称,不包括扩展名exe</param>
/// <param name="processFileName">进程文件的完整路径</param>
/// <returns>存在返回true,否则返回false</returns>
public static bool CheckProcessExists(string processName, string processFileName)
{
Process[] processes = Process.GetProcessesByName(processName);
foreach (Process p in processes)
{
if (!string.IsNullOrEmpty(processFileName))
{
if (processFileName == p?.MainModule?.FileName)
{
return true;
}
}
else
{
return true;
}
}
return false;
}
#endregion
#region 结束指定的windows进程
/// <summary>
/// 结束指定的windows进程,如果进程存在
/// </summary>
/// <param name="processName">进程名称,不包含扩展名</param>
/// <param name="processFileName">进程文件完整路径,如果为空则删除所有进程名为processName参数值的进程</param>
public static bool KillProcessExists(string processName, string processFileName)
{
try
{
Process[] processes = Process.GetProcessesByName(processName);
foreach (Process p in processes)
{
if (!string.IsNullOrEmpty(processFileName))
{
if (processFileName == p.MainModule.FileName)
{
p.Kill();
p.Close();
}
}
else
{
p.Kill();
p.Close();
}
}
Console.WriteLine(string.Format("成功结束[{0}]进程!", processes));
return true;
}
catch (Exception ex)
{
Console.WriteLine("结束指定的Widnows进程异常:" + ex.Message, ex);
return false;
}
}
#endregion
}
}
+292
View File
@@ -0,0 +1,292 @@
using System.Xml;
using System.Data;
using System.IO;
using System;
namespace MAX.Framework.Helpers
{
/// <summary>
/// Xml的操作公共类
/// </summary>
public class XmlHelper
{
#region 字段定义
/// <summary>
/// /// XML文件的物理路径
/// </summary>
private string _filePath = string.Empty;
/// <summary>
/// Xml文档
/// </summary>
private XmlDocument _xml;
/// <summary>
/// XML的根节点
/// </summary>
private XmlElement _element;
#endregion
#region 构造方法
/// <summary>
/// 实例化XmlHelper对象
/// </summary>
/// <param name="xmlFilePath">Xml文件的相对路径</param>
public XmlHelper(string xmlFilePath)
{
//获取XML文件的绝对路径
_filePath = xmlFilePath;
//创建一个XML对象
_xml = new XmlDocument();
if (File.Exists(xmlFilePath))
{
//加载XML文件
_xml.Load(xmlFilePath);
}
_element = _xml.DocumentElement;
}
public XmlHelper(Stream stream)
{
//创建一个XML对象
_xml = new XmlDocument();
if (stream != null)
{
//加载XML
_xml.Load(stream);
}
_element = _xml.DocumentElement;
}
#endregion
#region 获取指定XPath表达式的节点对象
/// <summary>
/// 获取指定XPath表达式的节点对象
/// </summary>
/// <param name="xPath">XPath表达式,
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
/// </param>
public XmlNode GetNode(string xPath)
{
//返回XPath节点
return _element.SelectSingleNode(xPath);
}
/// <summary>
/// 获取指定XPath表达式的节点对象
/// </summary>
/// <param name="xPath">XPath表达式,
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
/// </param>
public XmlNodeList GetNodes(string xPath)
{
//返回XPath节点
return _element.SelectNodes(xPath);
}
#endregion
#region 获取指定XPath表达式节点的值
/// <summary>
/// 获取指定XPath表达式节点的值
/// </summary>
/// <param name="xPath">XPath表达式,
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
/// </param>
public string GetValue(string xPath)
{
//返回XPath节点的值
string value = _element.SelectSingleNode(xPath)?.InnerText ?? "";
return value;
}
public T GetValue<T>(string xPath, T? def = default)
{
string value = GetValue(xPath);
if (value == null)
return def;
else
return (T)Convert.ChangeType(value, typeof(T));
}
#endregion
#region 获取指定XPath表达式节点的属性值
/// <summary>
/// 获取指定XPath表达式节点的属性值
/// </summary>
/// <param name="xPath">XPath表达式,
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
/// </param>
/// <param name="attributeName">属性名</param>
public string GetAttributeValue(string xPath, string attributeName)
{
//返回XPath节点的属性值
return _element.SelectSingleNode(xPath).Attributes[attributeName].Value;
}
#endregion
#region 新增节点
/// <summary>
/// 1. 功能:新增节点。
/// 2. 使用条件:将任意节点插入到当前Xml文件中。
/// </summary>
/// <param name="xmlNode">要插入的Xml节点</param>
public void AppendNode(XmlNode xmlNode)
{
//导入节点
XmlNode node = _xml.ImportNode(xmlNode, true);
//将节点插入到根节点下
_element.AppendChild(node);
}
/// <summary>
/// 1. 功能:新增节点。
/// 2. 使用条件:将DataSet中的第一条记录插入Xml文件中。
/// </summary>
/// <param name="ds">DataSet的实例,该DataSet中应该只有一条记录</param>
public void AppendNode(DataSet ds)
{
//创建XmlDataDocument对象
XmlDataDocument xmlDataDocument = new XmlDataDocument(ds);
//导入节点
XmlNode node = xmlDataDocument.DocumentElement.FirstChild;
//将节点插入到根节点下
AppendNode(node);
}
#endregion
#region 删除节点
/// <summary>
/// 删除指定XPath表达式的节点
/// </summary>
/// <param name="xPath">XPath表达式,
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
/// </param>
public void RemoveNode(string xPath)
{
//获取要删除的节点
XmlNode node = _xml.SelectSingleNode(xPath);
//删除节点
_element.RemoveChild(node);
}
#endregion //删除节点
#region 保存XML文件
/// <summary>
/// 保存XML文件
/// </summary>
public void Save()
{
if (string.IsNullOrEmpty(_filePath))
{
throw new Exception("Xml文件路径不能为空!");
}
//保存XML文件
_xml.Save(_filePath);
}
public void Save(string filePath)
{
//保存XML文件
_xml.Save(filePath);
}
#endregion //保存XML文件
#region 静态方法
#region 创建根节点对象
/// <summary>
/// 创建根节点对象
/// </summary>
/// <param name="xmlFilePath">Xml文件的相对路径</param>
private static XmlElement CreateRootElement(string xmlFilePath)
{
//定义变量,表示XML文件的绝对路径
string filePath = "";
//获取XML文件的绝对路径
filePath = xmlFilePath;
//创建XmlDocument对象
XmlDocument xmlDocument = new XmlDocument();
//加载XML文件
xmlDocument.Load(filePath);
//返回根节点
return xmlDocument.DocumentElement;
}
#endregion
#region 获取指定XPath表达式节点的值
/// <summary>
/// 获取指定XPath表达式节点的值
/// </summary>
/// <param name="xmlFilePath">Xml文件的相对路径</param>
/// <param name="xPath">XPath表达式,
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
/// </param>
public static string GetValue(string xmlFilePath, string xPath)
{
//创建根对象
XmlElement rootElement = CreateRootElement(xmlFilePath);
//返回XPath节点的值
return rootElement.SelectSingleNode(xPath).InnerText;
}
#endregion
#region 获取指定XPath表达式节点的属性值
/// <summary>
/// 获取指定XPath表达式节点的属性值
/// </summary>
/// <param name="xmlFilePath">Xml文件的相对路径</param>
/// <param name="xPath">XPath表达式,
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
/// </param>
/// <param name="attributeName">属性名</param>
public static string GetAttributeValue(string xmlFilePath, string xPath, string attributeName)
{
//创建根对象
XmlElement rootElement = CreateRootElement(xmlFilePath);
//返回XPath节点的属性值
return rootElement.SelectSingleNode(xPath).Attributes[attributeName].Value;
}
#endregion
#endregion
}
public static class XmlHelExtension
{
public static string GetAttributeValue(this XmlNode node, string attributeName)
{
return node.Attributes[attributeName].Value;
}
public static T GetAttributeValue<T>(this XmlNode node, string attributeName)
{
var value = node.Attributes[attributeName].Value;
if (string.IsNullOrEmpty(value))
return default(T);
return (T)Convert.ChangeType(value, typeof(T));
}
}
}