黃聰:Delphi 中的 XMLDocument 類詳解(8) - 新增與刪除節點

weixin_34304013發表於2010-08-27
unit Unit1;

interface

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

type
TForm1
= class(TForm)
XMLDocument1: TXMLDocument;
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(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
newNode, newNodeAdd: IXMLNode;
begin
newNode :
= XMLDocument1.DocumentElement.AddChild('人員');
newNode.Attributes[
'職務'] := '祕書';

newNodeAdd :
= newNode.AddChild('姓名');
newNodeAdd.Text :
= '小翠';

newNodeAdd :
= newNode.AddChild('性別');
newNodeAdd.Text :
= '';

Memo1.Lines :
= XMLDocument1.XML; {檢視}
{會在尾部增加:
<人員 職務="祕書"><姓名>小翠</姓名><性別>女</性別></人員>
}
end;


//刪除
procedure TForm1.Button2Click(Sender: TObject);
var
nodeList: IXMLNodeList;
begin
nodeList :
= XMLDocument1.DocumentElement.ChildNodes;
nodeList.Delete(nodeList.Count
-1); {刪除最後一條}

Memo1.Lines :
= XMLDocument1.XML; {檢視}
end;

end.

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

出處:http://www.cnblogs.com/del/archive/2008/01/03/1024681.html

相關文章