一、XML文件(x1.xml):node
<?xml version="1.0" encoding="utf-8" ?> <itcast> <itcastNet> <net0405> <student id="cz001"> <name>張三</name> <age>18</age> <gender>Male</gender> </student> <student id="cz002"> <name>李四</name> <age>19</age> <gender>Female</gender> </student> </net0405> <netHeiMa> <student id="hm001"> <name>楊廉壬</name> <age>20</age> <gender>Male</gender> </student> <student id="hm002"> <name>何聖東</name> <age>10</age> <gender>Male</gender> </student> </netHeiMa> </itcastNet> </itcast>
二、主程序:spa
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml.Linq; namespace _04Xml遍歷遞歸顯示到TreeView上 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { XDocument xdoc = XDocument.Load("x1.xml");//1.加載x1.xml XElement xeRoot = xdoc.Root;//2.獲取根節點 //3.把根節點加到TreeView上。 TreeNode treeViewRoot = treeView1.Nodes.Add(xeRoot.Name.ToString()); LoadNodes(xeRoot, treeViewRoot);//4.遞歸加載 } private void LoadNodes(XElement xeRoot, TreeNode treeViewRoot) { //把xeRoot下面的內容循環綁定到treeViewRoot下面 foreach (XElement ele in xeRoot.Elements()) { if (ele.Elements().Count() > 0) { //把元素自己綁定上來 TreeNode node = treeViewRoot.Nodes.Add(ele.Name.ToString()); XAttribute attr = ele.Attribute("id");//若是元素還有屬性的話,把屬性也綁定上來。 if (attr != null)//表示有id屬性 { node.Text += "[" + attr.Name + "=" + attr.Value + "]"; } LoadNodes(ele, node); } else { TreeNode node = treeViewRoot.Nodes.Add(ele.Value); } } } } }
三、運行結果:code