using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace test2
{
class XmlHelpe
{
private string path;
private XmlDocument doc = new XmlDocument();
/// <summary>
/// 带有一个路径的参数构造方法
/// </summary>
/// <param name="path"></param>
public XmlHelpe(string path)
{
this.path = path;
}
/// <summary>
/// 创建根节点对象方法
/// </summary>
public void XmlElementS()
{
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(declaration);
}
/// <summary>
/// 创建XML的根节点方法
/// </summary>
/// <param name="ElementName">根节点名字</param>
public void XmlCreateElement(string ElementName)
{
doc.CreateElement(ElementName);
}
/// <summary>
/// 新增节点方法
/// </summary>
/// <param name="NodeName"></param>
/// <returns></returns>
public XmlElement XmlAppendNode( string NodeName)
{
return new XmlDocument().CreateElement(NodeName);
}
/// <summary>
/// 删除指定节点
/// </summary>
/// <param name="path">路径</param>
/// <param name="xmlName">删除的节点名</param>
public void XmlDeleteNode(string xmlName)
{
doc.Load(path);
XmlNode node = doc.SelectSingleNode(xmlName);
doc.RemoveChild(node);
}
/// <summary>
/// 保存XML文件方法
/// </summary>
public void XmlSave()
{
doc.Save(path);
}
/// <summary>
/// 获取指定XPath表达式节点的值方法
/// </summary>
/// <param name="Xpath"></param>
public string GetXpathValue(string Xpath)
{
doc.Load(path);
return doc.SelectSingleNode(Xpath).InnerText;
}
/// <summary>
/// 获取指定XPath表达式节点的属性值方法
/// </summary>
/// <param name="Xpath"></param>
/// <param name="name"></param>
/// <returns></returns>
public string GetXpathAttribute(string Xpath,string name)
{
doc.Load(path);
return doc.SelectSingleNode(Xpath).Attributes[name].Value;
}
/// <summary>
/// 获取指定XPath表达式的节点对象方法
/// </summary>
/// <param name="Xpath"></param>
/// <returns></returns>
public XmlNode GetXpath(string Xpath)
{
doc.Load(path);
return doc.SelectSingleNode(Xpath);
}
}
}