用遞迴方法,使用 xml 文檔產生 Treeview 樹形視圖。由於是動態產生,所以可以通過修改 xml 的邏輯來定製 Treeview 的結構,
從而實現了 xml 對 Treeview 的動態配置,而不用修改代碼。
xml 檔案如下:
<?xml version="1.0" encoding="gb2312"?>
<root topic="頻道列表" catalog="none">
<channel topic="作業系統" catalog="none">
<channel topic="Windows頻道" catalog="windows" />
<channel topic="DOS頻道" catalog="dos" />
<channel topic="Linux" catalog="linux" />
</channel>
<channel topic="菜鳥專區" catalog="cainiaozhuanqu" />
<channel topic="應用軟體" catalog="app" />
<channel topic="安全專區" catalog="safe" />
<channel topic="代碼實驗室" catalog="lab" />
<BBS topic="電腦學習社區" catalog="none">
<subBBS topic="子社區-1" catalog="sub1" />
<subBBS topic="子社區-2" catalog="sub2" />
</BBS>
</root>
程式碼如下:
unit tree_xml;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Forms, Dialogs, ComCtrls, StdCtrls, XMLDoc, XMLIntf;
type
TForm1 = class(TForm)
TreeView1: TTreeView;
Memo1: TMemo;
Button1: TButton;
procedure TreeView1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Button1Click(Sender: TObject);
private
function CreateTreeview(XmlNode: IXMLNode; TreeNode: TTreeNode):TTreeNode;
{ Private declarations }
public
{ Public declarations }
end;
type
pRec = ^TData;
TData = record
sCatalog: string;
sReserved: String
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function TForm1.CreateTreeview(XmlNode: IXMLNode; TreeNode: TTreeNode): TTreeNode;
var
i: integer;
ParentTreeNode, CurrentTreeNode: TTreeNode;
pData: pRec;
begin
New(pData);
pData^.sCatalog := XmlNode.AttributeNodes['catalog'].NodeValue;
CurrentTreeNode := TreeView1.Items.AddChildObject(TreeNode,
XmlNode.AttributeNodes['topic'].NodeValue, pData); //pointer(...)
if XmlNode.HasChildNodes then
begin
ParentTreeNode := CurrentTreeNode;
for i:=0 to XmlNode.ChildNodes.Count-1 do
begin
CreateTreeview(XmlNode.ChildNodes[i], ParentTreeNode);
end;
end;
result := CurrentTreeNode;
end;
{------------------------------------------------------------------}
procedure TForm1.TreeView1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var pData: pRec;
begin
pData := Treeview1.Selected.Data;
Memo1.Lines.Add(pData^.sCatalog);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
oXml: TXMLDocument;
begin
oXml := TXMLDocument.Create(self);
oXml.FileName := '_Treeview.xml';
oXml.Active:=true;
CreateTreeview(oXml.ChildNodes.FindNode('root'), Treeview1.Items.GetFirstNode);
Treeview1.FullExpand; //節點全部展開
oXml.Free;
end;
end.
注意程式中 Treeview 的 TreeView1.Items.AddChildObject 方法,其最後一個參數用來儲存該節點的相關資料,是一個指標類型的資料,使用時要格外小心。本例中,先定義一個記錄類型,再定義一個指標指向它,然後作為 AddChildObject 的最後一個參數。記錄類型可以儲存節點的很多相關參數,本例中只用到了一個,實際使用時可以任意擴充。
---“十萬個為什麼”電腦學習網-http://www.why100000.com-原創文章
張慶(網眼)2007-10-22