public class XmlHelper
{
/// <summary>
/// XML文件的物理路径
/// </summary>
private string _filePath = string.Empty;
/// <summary>
/// Xml文档
/// </summary>
private XmlDocument _xml;
/// <summary>
/// XML的根节点
/// </summary>
private XmlElement _element;
/// <summary>
/// 实例化XmlHelper对象
/// </summary>
/// <param name="xmlFilePath">Xml文件的绝对路径</param>
public XmlHelper(string xmlFilePath)
{
//获取XML文件的绝对路径
_filePath = xmlFilePath;
}
/// <summary>
/// 创建XML的根节点
/// </summary>
private void CreateXMLElement()
{
//创建一个XML对象
_xml = new XmlDocument();
if (System.IO.File.Exists(_filePath))
{
//加载XML文件
_xml.Load(this._filePath);
}
//为XML的根节点赋值
_element = _xml.DocumentElement;
}
/// <summary>
/// 新增节点方法
/// </summary>
/// <param name="xmlNode">要插入的Xml节点</param>
public void AppendNode(XmlNode xmlNode)
{
//创建XML的根节点
CreateXMLElement();
//导入节点
XmlNode node = _xml.ImportNode(xmlNode, true);
//将节点插入到根节点下
_element.AppendChild(node);
}
/// <summary>
/// 删除节点
/// </summary>
/// <param name="xPath">需要删除的节点</param>
public void RemoveNode(string xPath)
{
//创建XML的根节点
CreateXMLElement();
//获取要删除的节点
XmlNode node = _xml.SelectSingleNode(xPath);
//删除节点
_element.RemoveChild(node);
}
/// <summary>
/// 保存XML文件
/// </summary>
public void Save()
{
//创建XML的根节点
CreateXMLElement();
//保存XML文件
_xml.Save(this._filePath);
}
/// <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;
}
/// <summary>
/// 获取指定XPath表达式节点的值
/// </summary>
/// <param name="xmlFilePath">Xml绝对路径</param>
/// <param name="xPath">XPath表达式</param>
/// <returns></returns>
public static string GetValue(string xmlFilePath, string xPath)
{
//创建根对象
XmlElement rootElement = CreateRootElement(xmlFilePath);
//返回XPath节点的值
return rootElement.SelectSingleNode(xPath).InnerText;
}
/// <summary>
/// 获取指定XPath表达式节点的属性值
/// </summary>
/// <param name="xmlFilePath">xml绝对路径</param>
/// <param name="xPath">XPath表达式</param>
/// <param name="attributeName">属性名</param>
/// <returns></returns>
public static string GetAttributeValue(string xmlFilePath, string xPath, string attributeName)
{
//创建根对象
XmlElement rootElement = CreateRootElement(xmlFilePath);
//返回XPath节点的属性值
return rootElement.SelectSingleNode(xPath).Attributes[attributeName].Value;
}
/// <summary>
/// 获取指定XPath表达式的节点对象方法
/// </summary>
/// <param name="xPath">XPath表达式</param>
/// <returns></returns>
public XmlNode GetNode(string xPath)
{
XmlDocument xml = new XmlDocument();
xml.Load(_filePath);
//创建根对象
XmlElement element = xml.DocumentElement;
return element.SelectSingleNode(xPath);
}
}