标签:
1、XML文件(x1.xml):
<?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>
2、主程序:
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); } } } } }
3、运行结果:
05-XML遍历递归显示到TreeView上(XDocument类)
标签:
原文地址:http://www.cnblogs.com/zy-style/p/4290186.html