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;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(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');
end;
//獲取根目錄下的元素數(1)
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(IntToStr(XMLDocument1.DocumentElement.ChildNodes.Count)); {4}
{DocumentElement 是根節點}
{ChildNodes 是節點包含的子節點的列表}
end;
//獲取根目錄下的元素數(2)
procedure TForm1.Button2Click(Sender: TObject);
var
nodeList: IXMLNodeList; {定義一個節點列表對象}
begin
nodeList := XMLDocument1.DocumentElement.ChildNodes;
{把根節點下的子節點列表賦給節點列表對象}
ShowMessage(IntToStr(nodeList.Count)); {4}
end;
//獲取根目錄下的元素數(3)
procedure TForm1.Button3Click(Sender: TObject);
var
node: IXMLNode; {定義一個節點對象}
nodeList: IXMLNodeList; {定義一個節點列表對象}
begin
node := XMLDocument1.DocumentElement;
{根節點也是一個節點, 把它賦給節點對象}
nodeList := node.ChildNodes;
ShowMessage(IntToStr(nodeList.Count)); {4}
end;
end.