C#操作Xml文件
1 using System;
2 using System.Text;
3 using System.Xml;
4
5 class XmlOperate
6 {
7 private XmlDocument xmlDocument;
8
9 private void CreateXmlFile(string filePath)
10 {
11 xmlDocument = new XmlDocument();
12 XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "utf-8", "yes");
13 XmlElement schoolElement = xmlDocument.CreateElement("school");
14 XmlElement studentElement = xmlDocument.CreateElement("student");
15 XmlElement nameElement = xmlDocument.CreateElement("name");
16 nameElement.InnerText = "张三";
17 studentElement.AppendChild(nameElement);
18 XmlElement ageElement = xmlDocument.CreateElement("age");
19 ageElement.InnerText = "19";
20 studentElement.AppendChild(ageElement);
21 XmlElement sexElement = xmlDocument.CreateElement("sex");
22 sexElement.InnerText = "男";
23 studentElement.AppendChild(ageElement);
24 schoolElement.AppendChild(studentElement);
25 xmlDocument.AppendChild(xmlDeclaration);
26 xmlDocument.AppendChild(schoolElement);
27 xmlDocument.Save(filePath);
28 }
29
30 private void ReadXmlFile(string fileName)
31 {
32 XmlDocument xmlDocument = new XmlDocument();
33 xmlDocument.Load(fileName);
34 XmlNode Node = xmlDocument.DocumentElement;
35 foreach (XmlNode item in Node)
36 {
37 Console.WriteLine("节点名称:" + item.Name);
38 foreach (XmlNode studentNode in item)
39 {
40 switch (studentNode.Name)
41 {
42 case "name":
43 Console.WriteLine("姓名:" + studentNode.InnerText);
44 break;
45 case "age":
46 Console.WriteLine("年龄:" + studentNode.InnerText);
47 break;
48 case "sex":
49 Console.WriteLine("性别:" + studentNode.InnerText);
50 break;
51 }
52 }
53 }
54 }
55
56 private void AddElement(XmlDocument xmlDocument)
57 {
58 XmlNode studentNode = xmlDocument.DocumentElement.SelectSingleNode("student");
59 XmlElement addressElement = xmlDocument.CreateElement("address");
60 addressElement.SetAttribute("city", "襄樊");
61 addressElement.InnerText = "樊城区19号";
62 studentNode.AppendChild(addressElement);
63
64 }
65
66 private void DeleteElement(XmlDocument xmlDocument)
67 {
68 XmlNode studentNode = xmlDocument.DocumentElement.SelectSingleNode("student");
69 foreach (XmlNode item in studentNode)
70 {
71 if (item.Name == "address")
72 {
73 studentNode.RemoveChild(item);
74 }
75 }
76 }
77
78 static void Main(string[] args)
79 {
80 string filePath = "c:\\school.xml";
81 XmlOperate xml = new XmlOperate();
82 //xml.CreateXmlFile(filePath);
83 //xml.ReadXmlFile(filePath);
84 xml.xmlDocument = new XmlDocument();
85 xml.xmlDocument.Load(filePath);
86 //xml.AddElement(xml.xmlDocument);
87 xml.DeleteElement(xml.xmlDocument);
88 xml.xmlDocument.Save(filePath);
89 }
90
91 }