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
procedure CreateTreevIEw(XmlNode: IXMLNode; TreeNode: TTreeNode);
{ Private declarations }
public
{ Public declarations }
end;
type
pRec = ^TData;
TData = record
sCatalog: string;
sReserved: String
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.CreateTreevIEw(XmlNode: IXMLNode; TreeNode: 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;
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 的最後一個參數。記錄類型可以保存節點的很多相關參數,本例中只用到了一個,實際使用時可以任意擴充。