Delphi中⽤Xml配置⽂档⽣成Treeview
⽤递归⽅法,使⽤ 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 }
delphi append;
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 := '_l';
oXml.Active:=true;
CreateTreeview(oXml.ChildNodes.FindNode('root'), Treeview1.Items.GetFirstNode);
Treeview1.FullExpand; //节点全部展开
oXml.Free;
end;
end.
注意程序中 Treeview 的 TreeView1.Items.AddChildObject ⽅法,其最后⼀个参数⽤来保存该节点的相关数据,是⼀个指针类型的数据,使⽤时要格外⼩⼼。本例中,先定义⼀个记录类型,再定义⼀个指针指向它,然后作为 AddChildObject 的最后⼀个参数。记录类型可以保存节点的很多相关参数,本例中只⽤到了⼀个,实际使⽤时可以任意扩充

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。