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); }
本文详细介绍如何使用C#进行XML文档的创建与读取操作。包括创建XML文档、添加节点声明、添加元素及其属性,以及如何读取XML文档并解析其内容。
1540

被折叠的 条评论
为什么被折叠?



