unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, xmldom, XMLIntf, StdCtrls, msxmldom, XMLDoc;

type
  TForm1 = class(TForm)
    XMLDocument1: TXMLDocument;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

//利用 XML 属性创建 xml 文件
procedure TForm1.Button1Click(Sender: TObject);
begin
  XMLDocument1.XML.Clear;
  XMLDocument1.XML.Add('');
  XMLDocument1.XML.Add('<科室名单 备注="测试">');
  XMLDocument1.XML.Add('<人员 职务="科长" 备注="正局级">');
  XMLDocument1.XML.Add('<姓名>张三');
  XMLDocument1.XML.Add('<性别>男');
  XMLDocument1.XML.Add('<年龄>34');
  XMLDocument1.XML.Add('');
  XMLDocument1.XML.Add('');

  {查看}
  ShowMessage(XMLDocument1.XML.Text);

  {保存}
  XMLDocument1.Active := True;
  XMLDocument1.SaveToFile('c:\temp\1.xml');
end;


//创建 xml 文件的标准方法
procedure TForm1.Button2Click(Sender: TObject);
var
  pNode,cNode: IXMLNode; {定义两个节点: 父节点、子节点}
begin
  XMLDocument1.XML.Clear;
  XMLDocument1.Active := True;                {必须先激活}
  XMLDocument1.Version := '1.0';              {设置版本}
  XMLDocument1.Encoding := 'GB2312';          {设置语言}

  pNode := XMLDocument1.AddChild('科室名单'); {添加的第一个节点是根节点, 现在的 pNode 是根节点}
  pNode.SetAttribute('备注', '测试');         {为根节点设置属性}

  pNode := pNode.AddChild('人员');            {为根节点添加子节点, 现在的 pNode 是 "人员" 节点}
  pNode.SetAttribute('职务', '科长');         {设置属性}
  pNode.SetAttribute('备注', '正局级');

  cNode := pNode.AddChild('姓名');  {为 pNode 添加子节点, 返回值 cNode 指向了新添加的节点}
  cNode.Text := '张三';

  cNode := pNode.AddChild('性别');
  cNode.Text := '男';

  cNode := pNode.AddChild('年龄');
  cNode.Text := '34';

  {查看}
  ShowMessage(XMLDocument1.XML.Text);

  {保存}
  XMLDocument1.SaveToFile('c:\temp\2.xml');
end;

end.

posted on 2008-01-05 21:37  万一  阅读(16330)  评论(7编辑  收藏  举报