利用TreeList加载XML文件
第一次学习弄,也是上网看别人的思路,主要就是首先将XML读取到表里面,然后利用TreeList的两个属性:KeyFieldName和ParentFieldName两个属性的值,默认分别是ID,ParentID,二者的关系就是涉及到树形结构的层次关系。所创建的表中务必要包含二两个属性。下面上代码:
DataTable dt = new DataTable(); DataColumn did = new DataColumn("ID", Type.GetType("System.Int32")); DataColumn dParentID = new DataColumn("ParentID", Type.GetType("System.Int32")); DataColumn dNodeName = new DataColumn("节点名称", Type.GetType("System.String")); dt.Columns.Add(did); dt.Columns.Add(dParentID); dt.Columns.Add(dNodeName); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlPath); int Id = 1; int ParentId=0; //获取根节点 XmlElement xmlRootElement=xmlDoc.DocumentElement; DataRow dr = dt.NewRow(); dr["ID"] = Id++; dr["ParentID"] = 0; dr["节点名称"] = xmlRootElement.Name.ToString(); dt.Rows.Add(dr); XmlNodeList xmlNodeList = xmlRootElement.ChildNodes; foreach (XmlElement xmlElement in xmlNodeList) { dr = dt.NewRow(); dr["ID"] = Id++; dr["ParentID"] = ParentId; dr["节点名称"] = xmlElement.Name.ToString(); dt.Rows.Add(dr); int parentId = Id-1; //遍历该节点下面的子节点 XmlNodeList ChildNodeList = xmlElement.ChildNodes; foreach (XmlNode xmlNode in ChildNodeList) { dr = dt.NewRow(); dr["ID"] = Id++; dr["ParentID"] = parentId; dr["节点名称"] = xmlNode.Name.ToString(); dt.Rows.Add(dr); } } this.treeList1.DataSource=dt;