遍历XML文件添加到TreeView递归调用

来源:互联网 发布:辩论电视网络 编辑:程序博客网 时间:2024/05/21 10:20
 using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Xml.Linq;namespace 遍历XML文件添加到TreeView递归调用{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e)        {            //读取xml文件            XDocument xdoc = XDocument.Load("11.xml");            XElement root = xdoc.Root;//获取根元素            TreeNode tn = tv.Nodes.Add(root.Name.ToString());//根元素的名字显示到控件上            LoadXElement(root, tn);        }        private void LoadXElement(XElement root, TreeNode tn)        {            foreach(XElement item in root.Elements())//遍历根元素下所有的子元素            {                //判断当前的元素下是否还有元素                if(item.Elements().Count()>0)                {                    TreeNode tn1 = tn.Nodes.Add(item.Name.ToString());                    LoadXElement(item, tn1);//递归调用                }                else                {                    tn.Nodes.Add(item.Value);                }            }        }    }}
0 0
原创粉丝点击