用递归方法,使用 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 的最后一个参数。记录类型可以保存节点的很多相关参数,本例中只用到了一个,实际使用时可以任意扩充
转载于:https://www.cnblogs.com/OneSpeak/articles/1775256.html