unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, xmldom, XMLIntf, msxmldom, XMLDoc, StdCtrls;
type
TForm1 = class(TForm)
XMLDocument1: TXMLDocument;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
//打開
procedure TForm1.FormCreate(Sender: TObject);
begin
XMLDocument1.LoadFromFile('c:\temp\test.xml');
{必須用萬一提供的 XML 測試文件, 才能有相同的返回值}
end;
//訪問第一個人的信息
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(XMLDocument1.DocumentElement.ChildNodes[0].ChildNodes['姓名'].Text); {張三}
ShowMessage(XMLDocument1.DocumentElement.ChildNodes[0].ChildNodes['性別'].Text); {男}
ShowMessage(XMLDocument1.DocumentElement.ChildNodes[0].ChildNodes['年齡'].Text); {34}
{可以通過位置訪問子節點, 如: ChildNodes[0] 表示子節點列表中的第一個元素}
{可以通過子節點名訪問子節點, 如: ChildNodes['姓名']}
{但在節點名一樣的情況下, 只能通過位置訪問}
{任何情況下都可以通過位置訪問, 譬如:}
ShowMessage(XMLDocument1.DocumentElement.ChildNodes[0].ChildNodes[0].Text); {張三}
end;
//訪問第二個人的信息
procedure TForm1.Button2Click(Sender: TObject);
var
nodeList: IXMLNodeList;
node: IXMLNode;
begin
nodeList := XMLDocument1.DocumentElement.ChildNodes;
node := nodeList[1];
ShowMessage(node.ChildNodes['姓名'].Text); {李四}
ShowMessage(node.ChildNodes['性別'].Text); {女}
ShowMessage(node.ChildNodes['年齡'].Text); {43}
end;
//獲取所有成員姓名
procedure TForm1.Button3Click(Sender: TObject);
var
nodeList: IXMLNodeList;
node: IXMLNode;
num,i: Integer;
begin
nodeList := XMLDocument1.DocumentElement.ChildNodes;
num := nodeList.Count;
for i := 0 to num - 1 do
begin
node := nodeList[i];
ShowMessage(node.ChildNodes['姓名'].Text); {會分別顯示: 張三 李四 王五 孫六}
end;
end;
//獲取所有成員年齡
procedure TForm1.Button4Click(Sender: TObject);
var
nodeList: IXMLNodeList;
node: IXMLNode;
num,i: Integer;
begin
nodeList := XMLDocument1.DocumentElement.ChildNodes;
num := nodeList.Count;
for i := 0 to num - 1 do
begin
node := nodeList[i];
ShowMessage(node.ChildValues['年齡']); {會分別顯示: 34 43 25 52}
end;
end;
end.