XML——>treeciew ...
XML——>treeciew
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Xml; namespace TreeExXML { class TreeExXMLCls { private TreeView thetreeview; private string xmlfilepath; XmlDocument textdoc; public TreeExXMLCls() { //----構造函數 textdoc = new XmlDocument(); } ~TreeExXMLCls() { //----析構函數 } #region 遍歷XML並實現向tree的轉化 /// <summary> /// 遍歷treeview並實現向XML的轉化 /// </summary> /// <param name="XMLFilePath">XML輸出路徑</param> /// <param name="TheTreeView">樹控制項對象</param> /// <returns>0表示函數順利執行</returns> public int XMLToTree(string XMLFilePath, TreeView TheTreeView) { //-------重新初始化轉換環境變數 thetreeview = TheTreeView; xmlfilepath = XMLFilePath; //-------重新對XMLDocument對象賦值 textdoc.Load(xmlfilepath); XmlNode root = textdoc.SelectSingleNode("Sinumerik"); TreeNode bootTreeNode = new TreeNode(); bootTreeNode.Text = "Sinumerik"; thetreeview.Nodes.Add(bootTreeNode); foreach (XmlNode subXmlnod in root.ChildNodes) { //TreeNode trerotnod = new TreeNode(); TreeNode treeNode = new TreeNode(); XmlElement element = (XmlElement)subXmlnod; treeNode.Text = element .GetAttribute ("Title"); treeNode.ToolTipText = element.GetAttribute("Description"); bootTreeNode.Nodes.Add(treeNode ); //xml三層結構---從外到內 TransXML(subXmlnod.ChildNodes, treeNode); } return 0; } private int TransXML(XmlNodeList Xmlnodes, TreeNode partrenod) { //------遍歷XML中的所有節點,仿照treeview節點遍歷函數 foreach (XmlNode xmlnod in Xmlnodes) { TreeNode subtreeNode = new TreeNode(); XmlElement element = (XmlElement)xmlnod ; subtreeNode.Text = element.GetAttribute("Title"); subtreeNode.ToolTipText = element.GetAttribute("Description"); subtreeNode.Tag = element.GetAttribute("nodeClass"); partrenod.Nodes.Add(subtreeNode); if (xmlnod.ChildNodes.Count > 0) { TransXML(xmlnod.ChildNodes, subtreeNode); } } return 0; } #endregion } }