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.

posted on 2008-01-03 13:51  万一  阅读(11924)  评论(11编辑  收藏  举报