效果:
代码:
1 XmlDocument xml = new XmlDocument(); 2 private void Form1_Load(object sender, EventArgs e) 3 { 4 CreateXML(); 5 TreeNode tn = new TreeNode("魔兽"); 6 treeView1.Nodes.Add(tn); 7 xml.Load(@"D:XMLFile.xml"); 8 XmlNode nod = xml.DocumentElement; 9 int i = 0; 10 foreach (XmlNode xn in nod.ChildNodes) 11 { 12 treeView1.TopNode.Nodes.Add(xn.Attributes["two"].Value); 13 14 foreach (XmlNode xn2 in xn.ChildNodes) 15 { 16 treeView1.TopNode.Nodes[i].Nodes.Add(xn2.InnerText); 17 } 18 i++; 19 } 20 } 21 public void CreateXML() 22 { 23 //创建xml文件 24 XmlDeclaration dec = xml.CreateXmlDeclaration("1.0", "utf-8", null); 25 xml.AppendChild(dec); 26 //添加树形字段 27 XmlElement one = xml.CreateElement("one"); 28 XmlElement two = xml.CreateElement("two"); 29 XmlElement two1 = xml.CreateElement("two"); 30 XmlElement three = xml.CreateElement("three"); 31 XmlElement threeDL = xml.CreateElement("three"); 32 XmlElement three1 = xml.CreateElement("three"); 33 XmlElement three10 = xml.CreateElement("three"); 34 //添加树形结构关系 35 xml.AppendChild(one); 36 one.AppendChild(two); 37 one.AppendChild(two1); 38 two.AppendChild(three); 39 two.AppendChild(threeDL); 40 two1.AppendChild(three1); 41 two1.AppendChild(three10); 42 //添加属性 43 two.SetAttribute("two", "不死"); 44 two1.SetAttribute("two", "暗夜"); 45 //添加内容 46 three.InnerText = "DK"; 47 threeDL.InnerText = "DL"; 48 three1.InnerText = "DH"; 49 three10.InnerText = "WD"; 50 xml.Save(@"D:XMLFile.xml"); 51 }