读取xml文件内容,并将其内容以treeview的方式展现出来
xml文件内容:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="utf-8" ?> <folder> <folderOne name="一级文件夹"> <folderTwo name="二级文件夹"> <folderThree name="三级文件加">哈哈你发现我了</folderThree> </folderTwo> </folderOne> <folderOne name="一级文件夹"> <folderTwo name="二级文件夹"> <folderThree name="三级文件加">我是第二个</folderThree> </folderTwo> </folderOne> <folderOne name="一级文件夹"> <folderTwo name="二级文件夹"> <folderThree name="三级文件加">我是第三个</folderThree> </folderTwo> </folderOne> <folderOne name="一级文件夹"> <folderTwo name="二级文件夹"> <folderThree name="三级文件加">我是第四个</folderThree> </folderTwo> </folderOne> </folder>
C#代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private void btnLoad_Click(object sender, EventArgs e) { //加载xml文件 XDocument xdoc = XDocument.Load("Folders.xml"); //获取根元素,并且绑定到树上 XElement xRoot = xdoc.Root; this.treeView.Nodes.Add(xRoot.Name.ToString()); //递归遍历根元素下面所有元素 GetAllFolders(xRoot,treeView.Nodes[0]); } //递归加载xml中的所有子元素 private void GetAllFolders(XElement elment, TreeNode treeNode) { foreach (XElement item in elment.Elements()) { TreeNode node; if (item.Elements().Count()>0) { node = treeNode.Nodes.Add(item.Attribute("name").Value); GetAllFolders(item, node); } else {//如果是最后一个元素,加载的就是这个元素的内容,而不是节点属性 node = treeNode.Nodes.Add(elment.Value); } } }