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');
{必須用萬一提供的 XML 測試文件, 才能有相同的返回值}
end;
//獲取根元素屬性
procedure TForm1.Button1Click(Sender: TObject);
var
nodeList: IXMLNodeList;
node: IXMLNode;
begin
ShowMessage(IntToStr(XMLDocument1.DocumentElement.AttributeNodes.Count)); {1}
ShowMessage(XMLDocument1.DocumentElement.Attributes['備注']); {測試}
{通過屬性名訪問屬性, 一般用 Attributes['屬性名']}
ShowMessage(XMLDocument1.DocumentElement.AttributeNodes[0].Text); {測試}
{通過屬性位置訪問屬性, 必須用 AttributeNodes[位置ID]}
{但通過 AttributeNodes['屬性名'] 也可以訪問屬性, 譬如:}
ShowMessage(XMLDocument1.DocumentElement.AttributeNodes['備注'].Text); {測試}
{AttributeNodes 是某個節點的屬性列表, 它也是一個節點列表對象, 譬如:}
nodeList := XMLDocument1.DocumentElement.AttributeNodes;
node := nodeList[0];
ShowMessage(node.Text); {測試}
node := nodeList['備注'];
ShowMessage(node.Text); {測試}
end;
//訪問第二個人的屬性信息
procedure TForm1.Button2Click(Sender: TObject);
var
nodeList: IXMLNodeList;
node: IXMLNode;
begin
nodeList := XMLDocument1.DocumentElement.ChildNodes;
node := nodeList[1];
ShowMessage(IntToStr(node.AttributeNodes.Count)); {1}
ShowMessage(node.Attributes['職務']); {副科長}
ShowMessage(node.AttributeNodes[0].Text); {副科長}
end;
//訪問某個節點的所有屬性
procedure TForm1.Button3Click(Sender: TObject);
var
nodeList: IXMLNodeList;
node: IXMLNode;
num,i: Integer;
begin
nodeList := XMLDocument1.DocumentElement.ChildNodes;
node := nodeList[0];
num := node.AttributeNodes.Count;
for i := 0 to num - 1 do
begin
ShowMessage(node.AttributeNodes[i].Text); {會分別顯示: 科長 正局級}
end;
end;
end.