您的位置:首页 > 编程语言 > Delphi

黄聪:Delphi 中的 XMLDocument 类详解(6) - 访问节点属性

2010-08-27 11:06 507 查看
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.

--------------------------------------------------------------------------------------------------------------------------------

出处:http://www.cnblogs.com/del/archive/2008/01/03/1024555.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐