1---保存XML文档
private void btnSave_Click(object sender, RoutedEventArgs e) { XmlDocument MyXmlDocument = new XmlDocument(); //添加节点声明 XmlDeclaration MyXmlDeclaration = MyXmlDocument.CreateXmlDeclaration("1.0","UTF-8",null); MyXmlDocument.AppendChild(MyXmlDeclaration); //添加Config标记 XmlElement MyConfig = MyXmlDocument.CreateElement("Config"); MyXmlDocument.AppendChild(MyConfig); //添加节点信息 XmlElement Student_1 = MyXmlDocument.CreateElement("Student"); XmlElement Student_2 = MyXmlDocument.CreateElement("Student"); MyConfig.AppendChild(Student_1); MyConfig.AppendChild(Student_2); //添加子节点信息 XmlElement Name_1 = MyXmlDocument.CreateElement("Name"); XmlElement Age_1 = MyXmlDocument.CreateElement("Age"); XmlElement Name_2 = MyXmlDocument.CreateElement("Name"); XmlElement Age_2 = MyXmlDocument.CreateElement("Age"); Name_1.InnerText = "张三"; Age_1.InnerText = "18"; Student_1.AppendChild(Name_1); Student_1.AppendChild(Age_1); Name_2.InnerText = "李四"; Age_2.InnerText = "18"; Student_2.AppendChild(Name_2); Student_2.AppendChild(Age_2); MyXmlDocument.Save("C:\\Users\\Newland\\Desktop\\Myxml.xml"); }
2---读取XML文档
private void btnRead_Click(object sender, RoutedEventArgs e) { this.listView.Items.Clear(); //读取XML文档 XmlDocument MyXmlDocument = new XmlDocument(); MyXmlDocument.Load("C:\\Users\\Newland\\Desktop\\Myxml.xml"); //查找子节点 XmlNode MyConfig = MyXmlDocument.SelectSingleNode("Config"); XmlNodeList list = MyConfig.ChildNodes; this.listView.Items.Add(list[0].SelectSingleNode("Name").InnerText); this.listView.Items.Add(list[0].SelectSingleNode("Age").InnerText); this.listView.Items.Add(list[1].SelectSingleNode("Name").InnerText); this.listView.Items.Add(list[1].SelectSingleNode("Age").InnerText); }