上次的递归调用进行对XML文件读取限制比较大,这次静态进行读取,思路还是先把XML读取到DataTable中然后进行绑定,代码入下:
private DataTable CreatTable() { DataTable dt = new DataTable(); dt.Columns.Add("ID"); dt.Columns.Add("ParentID"); dt.Columns.Add("Name"); XmlDocument xmlDoc=new XmlDocument(); xmlDoc.Load(g_filepath); XmlNode rootnode = xmlDoc.DocumentElement; dr = dt.NewRow(); int Id = 1; dr["ID"] = Id++; dr["ParentID"] = 0; dr["Name"] = rootnode.Name.ToString(); dt.Rows.Add(dr); if (rootnode.HasChildNodes) { XmlNodeList xmlnodelist = rootnode.ChildNodes; foreach (XmlNode xmlnode in xmlnodelist) { dr = dt.NewRow(); dr["ID"] = Id++; dr["ParentID"] = 1; dr["Name"] = xmlnode.Name.ToString(); dt.Rows.Add(dr); if (xmlnode.HasChildNodes) { int j = 1; XmlNodeList nodelist = xmlnode.ChildNodes; foreach (XmlNode node in nodelist) { int pId=Id; dr = dt.NewRow(); dr["ID"] = Id++; dr["ParentID"] =pId-j ; dr["Name"] =node.Name.ToString(); dt.Rows.Add(dr); j++; if (node.HasChildNodes) { int i = 1; XmlNodeList list = node.ChildNodes; foreach (XmlNode Node in list) { if (Node.NodeType == XmlNodeType.Text) { continue; } else { int ppId = Id; dr = dt.NewRow(); dr["ID"] = Id++; dr["ParentID"] = ppId - i; dr["Name"] = Node.Name.ToString(); dt.Rows.Add(dr); i++; j++; } } } else { continue; } } } else { continue; } } } return dt; }原文链接:https://www.f2er.com/xml/298888.html