public class XMLHelper
{
public string Path { get; set; }//路径
//带有一个路径的参数构造方法
public XMLHelper(string path)
{
this.Path = path;
}
//创建xml并创建根节点
public void AddXml(string rootName)
{
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
XmlNode root = doc.CreateElement(rootName);
doc.AppendChild(root);
doc.Save(this.Path);
}
//新增节点
public void AddNode(string nodeName, string value)
{
XmlDocument doc = new XmlDocument();
doc.Load(this.Path);
XmlNode root = doc.DocumentElement;
XmlNode node = doc.CreateElement(nodeName);
node.InnerText = value;
root.AppendChild(node)
doc.Save(this.Path);
}
//删除节点方法
public void DelNode(string nodeName, string xpath)
{
XmlDocument doc = new XmlDocument();
doc.Load(this.Path);
XmlNode xmlNode = doc.SelectSingleNode(xpath);
foreach (XmlNode node in xmlNode.ChildNodes)
{
if (node.Name.Equals(nodeName))
{
xmlNode.RemoveChild(node);
break;
}
}
doc.Save(this.Path);
}
//保存文件
public void SaveXml(XmlDocument doc)
{
doc.Save(this.Path);
}
//创建根节点对象
public void AddRoot(string rootName)
{
//不知道是什么意思
}
//获取指定XPath表达式节点的值
public string GetNodeValue(string xpath)
{
string str = "";
XmlDocument doc = new XmlDocument();
doc.Load(this.Path);
XmlNode xmlNode = doc.SelectSingleNode(xpath);
foreach (XmlNode node in xmlNode.ChildNodes)//获取所有的子节点
{
str += node.InnerText + "-";
}
return str;
}
//获取指定XPath表达式节点的属性值方法
public string GetNodeNameValue(string xpath)
{
string str = "";
XmlDocument doc = new XmlDocument();
doc.Load(this.Path);
XmlNode xmlNode = doc.SelectSingleNode(xpath);
foreach (XmlNode node in xmlNode.ChildNodes)
{
str += node.Attributes["type"].Value + "-";
}
return str;
}
}
XML帮助类
最新推荐文章于 2020-08-10 17:12:58 发布