步步为营-21-xml的增删改查
1 增加(存在则添加,不存在则新建)
//对xml的操作-- XmlDocument doc = new XmlDocument(); if (File.Exists("Person.xml")) { //如果存在,加载文档 doc.Load("Person.xml"); //获取根节点 XmlElement person = doc.DocumentElement; XmlElement student = doc.CreateElement("Student"); student.SetAttribute("ID", "110"); XmlElement name = doc.CreateElement("Name"); name.InnerXml = "张三"; student.AppendChild(name); XmlElement age = doc.CreateElement("Age"); age.InnerXml = "110"; student.AppendChild(age); XmlElement gender = doc.CreateElement("Gender"); gender.InnerXml = "男"; student.AppendChild(gender); person.AppendChild(student); } else { //不存在创建 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.AppendChild(dec); XmlElement person = doc.CreateElement("Person"); doc.AppendChild(person); XmlElement student = doc.CreateElement("Student"); student.SetAttribute("ID", "0"); XmlElement name = doc.CreateElement("Name"); name.InnerXml = "逍遥小天狼"; student.AppendChild(name); XmlElement age = doc.CreateElement("Age"); age.InnerXml = "18"; student.AppendChild(age); XmlElement gender = doc.CreateElement("Gender"); gender.InnerXml = "男"; student.AppendChild(gender); person.AppendChild(student); } doc.Save("Person.xml");
2 查询
//02-1 先加载 doc.Load("Person.xml"); //02-2 获取根节点 XmlElement person = doc.DocumentElement; //02-3 将根节点下所有的子节点拿出来,放入到LNodeList中 XmlNodeList xnl = person.ChildNodes; //02-4 显示 foreach (XmlNode item in xnl) { Console.WriteLine(item.InnerText); }
2.2 获取属性
//02-5 获取属性-修改节点 //获取字节s的方法 XmlNodeList Students = person.SelectNodes("Student"); foreach (XmlNode item in Students) { Console.WriteLine(item.Attributes["ID"].Value); if (item.Attributes["ID"].Value=="110") { //获取子节点方法 修改节点 item["Name"].InnerXml = "修改了名字"; } } doc.Save("Person.xml");
3 另一种读取xml文件方法 x-path
#region 03-通过x-path获取数据 doc.Load("Person.xml"); //03-01 获取根节点 XmlElement person = doc.DocumentElement; XmlNode xn = person.SelectSingleNode("/Person/Student[@ID='110']/Name"); Console.WriteLine(xn.InnerText); #endregion
4 删除
//04-01 加载文件,找到根节点 doc.Load("Person.xml"); XmlElement person = doc.DocumentElement; person.RemoveAll(); Console.WriteLine("删除成功");
5 删除部分节点
//05-01 加载文件,找到根节点 doc.Load("Person.xml"); XmlElement person = doc.DocumentElement; XmlNode xn = person.SelectSingleNode("/Person/Student[@ID='110']/Age"); //注意不能直接删除,需要父节点删除 xn.ParentNode.RemoveAll(); Console.WriteLine("删除成功"); doc.Save("Person.xml");
6