C#如何操作XML文件
⒈XML?
XML是一种可扩展的标记语言
具有以下特点
1.严格区分大小写
2.标签成对出现
3.有且只有一个根节点
⒉XML的创建
1 <?xml version="1.0" encoding="utf-8" ?> 2 <Order> 3 <CustomerName>fanqi</CustomerName> 4 <Items> 5 <OrderItem Name="Money" count="100000000000000"/> 6 </Items> 7 </Order>
1 public static void create() 2 { 3 XmlDocument doc = new XmlDocument(); 4 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null); 5 doc.AppendChild(dec); //将版本和编码信息添加到文档的第一行 6 7 XmlElement order = doc.CreateElement("Order"); 8 doc.AppendChild(order); //添加一个根级目录 9 10 XmlElement customerName = doc.CreateElement("CustomerName"); 11 customerName.InnerText = "fanqi"; //InnerText放文本时使用,特殊字符会转义 12 //customerName.InnerXml = "<h1> haha </h1>"; //InnerXml放标签时使用 13 order.AppendChild(customerName); 14 15 XmlElement items = doc.CreateElement("Items"); 16 order.AppendChild(items); 17 18 XmlElement orderitem = doc.CreateElement("OrderItem"); 19 orderitem.SetAttribute("Name", "Money"); 20 orderitem.SetAttribute("count", "100000000000000"); 21 items.AppendChild(orderitem); 22 23 doc.Save("fanqi.xml"); 24 }
⒊XML追加
1 public static void add() 2 { 3 XmlDocument doc = new XmlDocument(); 4 if (File.Exists("fanqi.xml")) 5 { 6 doc.Load("fanqi.xml"); 7 XmlElement books = doc.DocumentElement; //获得文件的根节点 8 } 9 else 10 { 11 //不存在就创建呗 12 } 13 doc.Save("fanqi.xml"); 14 }
⒋读取不带属性的XML
1 public static void loadNoAttribute() 2 { 3 XmlDocument doc = new XmlDocument(); 4 if (File.Exists("fanqi.xml")) 5 { 6 doc.Load("fanqi.xml"); 7 XmlElement order = doc.DocumentElement; //获得文件的根节点 8 XmlNodeList nodeList = order.ChildNodes; 9 foreach(XmlNode item in nodeList) //遍历输出子节点内容 10 { 11 Console.WriteLine(item.InnerText); 12 } 13 } 14 }
⒌读取带有属性的XML
1 public static void loadAttribute() 2 { 3 XmlDocument doc = new XmlDocument(); 4 if (File.Exists("fanqi.xml")) 5 { 6 doc.Load("fanqi.xml"); 7 XmlNodeList nodeList = doc.SelectNodes("/Order/Items/OrderItem"); 8 foreach (XmlNode item in nodeList) 9 { 10 Console.WriteLine(item.Attributes["Name"].Value); 11 Console.WriteLine(item.Attributes["count"].Value); 12 } 13 } 14 }
⒍更改XML属性的值
1 public static void modifyAttribute() 2 { 3 XmlDocument doc = new XmlDocument(); 4 if (File.Exists("fanqi.xml")) 5 { 6 doc.Load("fanqi.xml"); 7 XmlNode xn = doc.SelectSingleNode("/Order/Items/OrderItem[@Name='fanqi']"); 8 xn.Attributes["count"].Value = "999999999999"; 9 doc.Save("fanqi.xml"); 10 } 11 }
⒎删除节点
1 public static void removeNode() 2 { 3 XmlDocument doc = new XmlDocument(); 4 if (File.Exists("fanqi.xml")) 5 { 6 doc.Load("fanqi.xml"); 7 XmlNode xn = doc.SelectSingleNode("/Order/Items"); 8 xn.RemoveAll(); 9 doc.Save("fanqi.xml"); 10 } 11 }