研究了两天,网上也看了不少资料,但都是静态绑定到TreeList,就是在已知道表的情况下进行绑定,表中已经把KeyFieldName和ParentFieldName的关系确定好了,比较死板。我需要的功能是自动根据XML进行确定KeyFieldName和ParentFieldName关系。所以确定二者关系就比较麻烦,我现在只能实现对三层的XML文件进行显示,四层的还会出错,正在进一步改进,记录如下:(草稿形式,不很规范,谅解)
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Title = "打开XML文件";
openFile.Filter = "XML文件(*.xml)|*.xml";
openFile.InitialDirectory = "C:\\";
openFile.ShowDialog();
string filepath = openFile.FileName;
this.treeList1.DataSource = SelectXml(filepath);
}
public static int parentId;
public static int Id;
private DataTable SelectXml(string xmlPath)
{
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);
//初始ID,ParentID
Id = 1;
parentId = 1;
//获取根节点
XmlElement xmlRootElement = xmlDoc.DocumentElement;
DataRow dr = dt.NewRow();
dr["ID"] = Id;
dr["ParentID"] = 0;
dr["节点名称"] = xmlRootElement.Name.ToString();
dt.Rows.Add(dr);
Id++;
int Id1 = Id,pId;
int b = parentId, d = Id; //记录递归后的ID,ParentId变化
XmlNodeList xmlNodeList = xmlRootElement.ChildNodes;
foreach (XmlElement xmlElement in xmlNodeList)
{
XmlNode xmlnode = (XmlNode)xmlElement;
dr = dt.NewRow();
dr["ID"] =d;
dr["ParentID"] = parentId;
dr["节点名称"] = xmlnode.Name.ToString();
dt.Rows.Add(dr);
Id1 = d;
pId = b+1;
sort(xmlnode, Id1,pId,dt,ref d,ref b); //利用ref记录随时变化
}
return dt;
}
private void sort(XmlNode xmlnode, int ID,int parentId,DataTable dt,ref int d,ref int b)
{
if (xmlnode.HasChildNodes)
{
XmlNodeList ChildNodeList = xmlnode.ChildNodes;
foreach (XmlNode xmlNode in ChildNodeList)
{
if (xmlNode.NodeType == XmlNodeType.Text)
{
Id = Id - 1;
ID = ID + 1;
continue;
}
else
{
ID = ID + 1;
DataRow dr = dt.NewRow();
dr["ID"] = ID;
dr["ParentID"] = parentId;
dr["节点名称"] = xmlNode.Name.ToString();
Id = Id + 1;
dt.Rows.Add(dr);
sort(xmlNode,ID, Id - 1, dt,ref d,ref b);
}
}
}
d=ID+1;
b = ID;
}