首页 > 学院 > 开发设计 > 正文

使用TreeView加载XML文件

2019-11-17 02:37:28
字体:
来源:转载
供稿:网友

使用TreeView加载xml文件

PS: 由于小弟初学编程,本文只写实现方式,代码写的不是很好请见谅!

1.需要读取的xml文档内容

2. 最终实现效果

3 貌似看起实现起来很复杂 但是想想还是挺简单

思路: 读取XML文档→获取XML根元素→ 递归添加根元素的子元素(因为树形的结构和XML很像)

具体看代码

首先给加载button注册方法

 1 PRivate void btn_LoadXml_Click(object sender, EventArgs e) 2         { 3             //读取Xml文件   this.txt_XmlPath.Text是文件路径        4             XDocument xmlfile = XDocument.Load(Path.GetFullPath(this.txt_XmlPath.Text.Trim()));  5  6             //取根元素 7             XElement rootElement = xmlfile.Root; 8  9             //给第TreeView 添加根节点 10             TreeNode node=  this.treeView1.Nodes.Add(rootElement.Name.ToString());11 12             RecursionAddNode(node.Nodes, rootElement);13         }
 RecursionAddNode方法代码 此方法主要实现递归添加到TreeView
private void RecursionAddNode(TreeNodeCollection nodes, XElement xElement)        {            //获取嵌套的元素            IEnumerable<XElement> elements = xElement.Elements();            //递归添加            foreach (XElement element in elements)            {                TreeNode node = nodes.Add(element.Name.ToString()+":"+GetAttributes(element));                RecursionAddNode(node.Nodes, element);            }        }
//如果要获取属性 就要再添加一个方法GetAttributes(element)
private static string GetAttributes(XElement xElement)        {            IEnumerable<XAttribute> attributes = xElement.Attributes();            foreach (XAttribute attribute in attributes)            {                return attribute.Name + "=" + attribute.Value;            }            return null;        }

备注:小弟才学读取XML 但是看了下文档 发现很多对象都能读取 所以想问我用这个对象读取过时了吗?


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表