1.判断xml是否存在
if (!File.Exists(url)) { XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", null); doc.AppendChild(dec); //创建一个根节点(一级) XmlElement root = doc.CreateElement("dataTable"); doc.AppendChild(root); //创建节点(二级) XmlElement element1 = doc.CreateElement("node"); element1.SetAttribute("title", "关于软件"); element1.SetAttribute("addTime", DateTime.Now.ToString("yyyyMMddHHmmssfffffff")); element1.InnerText = " 产品:node\n 版本:1.0\n 作者:HUJQ"; root.AppendChild(element1); doc.Save(url); }
2.读取xml
string title = null; string addTime = null; string node = null; XmlDocument doc = new XmlDocument(); doc.Load(url); // 得到根节点 XmlNode xn = doc.SelectSingleNode("dataTable"); // 得到根节点的所有子节点 XmlNodeList xnl = xn.ChildNodes; foreach (XmlNode xn1 in xnl) { // 将节点转换为元素,便于得到节点的属性值 XmlElement xe = (XmlElement)xn1; // 得到Type和ISBN两个属性的属性值 title = xe.GetAttribute("title").ToString(); addTime = xe.GetAttribute("addTime").ToString(); node = xe.InnerText; listBox1.Items.Add(title); dt.Rows.Add(listBox1.Items.Count, title, addTime, node); }
3.添加xml
XmlDocument doc = new XmlDocument(); doc.Load(url); //加载文件 XmlNode root = doc.SelectSingleNode("dataTable"); //创建节点(二级) XmlElement element1 = doc.CreateElement("node"); element1.SetAttribute("title", textBox_Title.Text); element1.SetAttribute("addTime", DateTime.Now.ToString("yyyyMMddHHmmssfffffff")); element1.InnerText = richTextBox_Node.Text; root.AppendChild(element1); doc.Save(url);//保存文件
4.修改xml
XmlDocument doc = new XmlDocument(); doc.Load(url); XmlNodeList nodeList = doc.SelectSingleNode("dataTable").ChildNodes;//获取dbGuest节点的所有子节点 foreach (XmlNode xn in nodeList)//遍历所有子节点 { XmlElement xe = (XmlElement)xn;//将子节点类型转换为aXmlElement类型 if (xe.GetAttribute("addTime") == dateTime) { xe.SetAttribute("title", textBox_Title.Text); xe.InnerText = richTextBox_Node.Text; } } doc.Save(url);
5.删除xml
XmlDocument doc = new XmlDocument(); doc.Load(url); XmlNodeList nodeList = doc.SelectSingleNode("dataTable").ChildNodes; foreach (XmlNode xn in nodeList)//遍历所有子节点 { XmlElement xe = (XmlElement)xn;//将子节点类型转换为aXmlElement类型 if (xe.GetAttribute("addTime") == dateTime) { xe.ParentNode.RemoveChild(xe); } } doc.Save(url);
时间: 2024-12-22 03:43:26