using System.Data;
using System.IO;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace Common.Utility
{
/// <summary>
/// Xml的操作公共类
/// </summary>
public class XmlHelper
{
#region 操作config文件
//创建或修改标准config文件
public void CreteFile(List<NodeInfo> dic, string appName)
{
bool isExistFile = File.Exists(appName);//是否已创建此文件
string file = isExistFile ? appName : GetProgramDataPath(appName);
if (!isExistFile)//无文件 则创建
{
XDocument xd = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("configuration", new XElement("appSettings", ""))
);
xd.Save(file);
}
//节点的CRUD
foreach (var item in dic)
{
if (item.NodeAction.ToLower() == "add")
AddNode(file, item.NodeKey, item.NodeValue);
else if (item.NodeAction.ToLower() == "update")
UpdateNode(file, item.NodeKey, item.NodeValue);
else if (item.NodeAction.ToLower() == "delete")
DeleteNode(file, item.NodeKey);
}
}
/// <summary>
/// 获得config文件存放目录
/// </summary>
/// <param name="appName">app名称</param>
/// <returns></returns>
public static string GetProgramDataPath(string appName)
{
string commPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);//获得“C:ProgramData”
string path = Path.Combine(commPath, "MyTemp");
Directory.CreateDirectory(path);//创建目录(存在,不重建不报错)。
return Path.Combine(path, appName + ".config");
}
#endregion
#region 查询节点
/// <summary>
/// 【查】通过key获得value属性值
/// </summary>
/// <param name="file">xml文件路径</param>
/// <param name="key"></param>
/// <param name="nodeName">节点名称 默认add</param>
/// <returns></returns>
public List<NodeInfo> GetNode(string file, string key = "", string nodeName = "add")
{
try
{
List<NodeInfo> list = new List<NodeInfo>();
XDocument doc = XDocument.Load(file);
if (key == "")//查询属性是key-value的所有add节点
{
var query = from q in doc.Descendants(nodeName)
where q.Attribute("key") != null && q.Attribute("value") != null
select q;
foreach (var item in query)
{
NodeInfo info = new NodeInfo();
info.NodeKey = item.FirstAttribute.Value;
info.NodeValue = item.LastAttribute.Value;
list.Add(info);
}
}
else
{
var query = from q in doc.Descendants(nodeName)
where q.Attribute("key") != null && q.Attribute("key").Value.Equals(key.Trim())
select q.Attribute("value").Value;
foreach (var item in query)
{
var v = query.First<string>();
NodeInfo info = new NodeInfo();
info.NodeKey = key.Trim();
info.NodeValue = v;
list.Add(info);
}
}
return list;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region 修改节点
/// <summary>
/// 【改】根据key修改value值
/// </summary>
/// <param name="file">xml文件路径</param>
/// <param name="key"></param>
/// <param name="val"></param>
public void UpdateNode(string file, string key, string val)
{
try
{
XDocument doc = XDocument.Load(file);
var r = from q in doc.Descendants("add")
where q.Attribute("key") != null && q.Attribute("key").Value.Equals(key.Trim())
select q;
//修改元素
if (r.Count() > 0)
{
XElement firstelement = r.First();
firstelement.RemoveAll();//删除此元素的所有属性
firstelement.SetAttributeValue("key", key);//设置新的属性
firstelement.SetAttributeValue("value", val);//设置新的属性
}
doc.Save(file);
}
catch (Exception ex)
{
}
}
#endregion
#region 新增节点
/// <summary>
/// 【增】增加一个add节点
/// </summary>
/// <param name="file">xml文件路径</param>
/// <param name="key"></param>
/// <param name="val"></param>
public void AddNode(string file, string key, string val)
{
try
{
XDocument doc = XDocument.Load(file); //导入XML文件
var r = from q in doc.Descendants("appSettings")
select q;
if (r.Count() > 0)
{
XElement firstelement = r.First();
var item = new XElement("add",
new XAttribute("key", key.Trim()),
new XAttribute("value", val.Trim())
);
firstelement.Add(item);
}
doc.Save(file);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region 删除节点
/// <summary>
/// 【删】根据key值删除对应的add节点
/// </summary>
/// <param name="file">xml文件路径</param>
/// <param name="key"></param>
public void DeleteNode(string file, string key)
{
try
{
XDocument doc = XDocument.Load(file); //导入XML文件
//查询修改的元素
var element = from e in doc.Descendants("add")
where e.Attribute("key") != null && e.Attribute("key").Value == key.Trim()
select e;
if (element.Count() > 0)
{
XElement firstelement = element.First();
firstelement.Remove();//删除节点
//firstelement.RemoveAll();//删除此元素的所有节点和属性 但是保留该对象父节点
//firstelement.RemoveAttributes(); //删除此元素的属性
//firstelement.RemoveNodes(); //删除此元素的子节点
}
doc.Save(file);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion //删除节点
}
/// <summary>
/// config中add节点实体类
/// </summary>
public class NodeInfo
{
public string NodeKey { get; set; }//key属性
public string NodeValue { get; set; }//value属性
public string NodeAction { get; set; }//节点操作,三类:add、update、delete
}
}
XmlHelper xml = new XmlHelper();
xml.AddNode(filePath, key, value);//加
xml.DeleteNode(filePath, key);//删
xml.UpdateNode(filePath, key, value);//改
xml.GetNode(FilePath)//查所有
xml.GetNode(FilePath, key)//查某个
[LINQ to XML]参考资料
1、2、3、4