Delphi 中用 Xml 配置文档生成 Treeview:
用递归方法,使用 xml 文档生成 Treeview 树形视图。由于是动态生成,所以可以通过修改 xml 的逻辑来定制 Treeview 的结构, 从而实现了 xml 对 Treeview 的动态配置,而不用修改代码。
- <?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 Unit1;
- interface
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs, ComCtrls, StdCtrls, XMLDoc, XMLIntf;
- type
- TForm1 = class(TForm)
- Memo1: TMemo;
- Button1: TButton;
- TreeView1: TTreeView;
- procedure TreeView1MouseDown(Sender: TObject; Button: TMouseButton;
- Shift: TShiftState; X, Y: Integer);
- procedure Button1Click(Sender: TObject);
- private
- { Private declarations }
- procedure CreateTreeview(XmlNode: IXMLNode; TreeNode: TTreeNode);
- 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 := 'PXML.xml';
- oXml.Active := true;
- CreateTreeview(oXml.ChildNodes.FindNode('root'), Treeview1.Items.GetFirstNode);
- Treeview1.FullExpand;
- oXml.Free;
- end;
- end.