第三方控制元件DevExpress的TreeList繫結XML檔案
研究了兩天,網上也看了不少資料,但都是靜態繫結到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;
}