c#xml追加读取节点
读取 if (File.Exists("Book.xml")) { XmlDocument doc = new XmlDocument(); doc.Load("Book.xml"); XmlElement root = doc.DocumentElement; XmlNodeList nodelist = root.ChildNodes; foreach (XmlNode item in nodelist) { Console.WriteLine(item.InnerText); } Console.ReadKey(); }
if (File.Exists("Book.xml")) { XmlDocument doc = new XmlDocument(); doc.Load("Book.xml"); XmlNodeList nodelist = doc.SelectNodes("/order/Items/OrderItem"); foreach (XmlNode item in nodelist) { Console.WriteLine(item.Attributes["Name"].Value); Console.WriteLine(item.Attributes["Count"].Value); } Console.ReadKey(); }
追加 static void Main(string[] args) { //XmlDocument xm = new XmlDocument(); //XmlDeclaration doc = xm.CreateXmlDeclaration("1.0", "utf-8", "yes"); //xm.AppendChild(doc); //XmlElement t1 = xm.CreateElement("order"); //xm.AppendChild(t1); //XmlElement t2 = xm.CreateElement("CustomerName"); //t1.AppendChild(t2); //t2.InnerXml = "<p>我是一个P标签</p>"; //XmlElement t3 = xm.CreateElement("CustomerNumber"); //t1.AppendChild(t3); //t3.InnerText = "<p>我是一个P标签</p>"; //XmlElement t4 = xm.CreateElement("Items"); //t1.AppendChild(t4); //XmlElement i1 = xm.CreateElement("OrderItem"); //t4.AppendChild(i1); //i1.SetAttribute("Name","码表"); //i1.SetAttribute("Count", "10"); //XmlElement i2 = xm.CreateElement("OrderItem"); //t4.AppendChild(i2); //i2.SetAttribute("Name", "雨衣"); //i2.SetAttribute("Count", "5"); //XmlElement i3 = xm.CreateElement("OrderItem"); //t4.AppendChild(i3); //i3.SetAttribute("Name", "手套"); //i3.SetAttribute("Count", "10"); //xm.Save("a.xml"); //有追加 没有 创建 XmlDocument xm = new XmlDocument(); XmlElement t1; XmlElement t2; XmlElement t3; if (File.Exists("1.xml")) { //加载xml文档到doc xm.Load("1.xml"); //获取根节点 t1 = xm.DocumentElement; } else { XmlDeclaration doc = xm.CreateXmlDeclaration("1.0", "utf-8", "yes"); xm.AppendChild(doc); t1 = xm.CreateElement("order"); xm.AppendChild(t1); } xm.Save("1.xml"); }
if (File.Exists("Book.xml")) { doc.Load("Book.xml"); //XmlNodeList nodelist = doc.SelectNodes("/order/Items"); XmlNode nodelist = doc.SelectSingleNode("/order/Items"); XmlElement orderitems = doc.CreateElement("orderitems"); orderitems.SetAttribute("Name", "雨衣"); orderitems.SetAttribute("Count", "10"); nodelist.AppendChild(orderitems); //foreach (XmlNode item in nodelist) //{ // item.AppendChild(orderitems); //} Console.ReadKey(); doc.Save("Book.xml"); }
删除XML if (File.Exists("Book.xml")) { XmlDocument doc = new XmlDocument(); doc.Load("Book.xml"); XmlNode nodelist = doc.SelectSingleNode("/order/Items"); nodelist.RemoveAll(); doc.Save("Book.xml"); Console.ReadKey(); }