jjw

写给自己的博客。 记录学习的点滴以备查。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

delphi XML简单处理

Posted on 2017-06-07 19:42  jjw  阅读(353)  评论(0编辑  收藏  举报
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Xml.XMLDoc, Xml.xmldom, Xml.XMLIntf,
  Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    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.Button1Click(Sender: TObject);
var
  IDoc: IXMLDocument;
  Root, N1, N2, N3: IXMLNode;
  I: Integer;
begin
  IDoc := TXMLDocument.Create(nil);
  IDoc.Active := True;
  Root := IDoc.AddChild('公司');
  for I := 1 to 9 do
  begin
    N1 := Root.AddChild('部门');
    N1.Attributes['Id'] := I;
    N1.AddChild('名称').NodeValue := '部门_'+I.ToString;
    N1.AddChild('主管').NodeValue := '主管_'+I.ToString;
  end;
  IDoc.SaveToFile('d:\jjw.xml');
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  Doc: IXMLDocument;
  Node: IXMLNode;
  I: Integer;
begin
  Doc := TXMLDocument.Create(nil);
  Doc.LoadFromFile('d:\jjw.xml');
  Doc.Active := True;
  Node := Doc.DocumentElement;
  for I := 0 to Node.ChildNodes.Count-1 do
    Node.ChildNodes[I].AddChild('人数').NodeValue := IntToStr(I+1);
  Doc.SaveToFile('d:\jjw.xml');
end;

procedure TForm1.Button3Click(Sender: TObject);
var
  Doc: IXMLDocument;
  Node: IXMLNode;
  I: Integer;
begin
  Doc := TXMLDocument.Create(nil);
  Doc.LoadFromFile('d:\jjw.xml');
  Doc.Active := True;
  Node := Doc.DocumentElement;
  for I := 0 to Node.ChildNodes.Count-1 do
    Node.ChildNodes[I].ChildNodes.Delete(2);
  Doc.SaveToFile('d:\jjw.xml');
end;

procedure TForm1.Button4Click(Sender: TObject);
var
  Doc: IXMLDocument;
  Root, Node: IXMLNode;
  I: Integer;
begin
  Doc := TXMLDocument.Create(nil);
  Doc.LoadFromFile('d:\jjw.xml');
  Doc.Active := True;
  Root := Doc.DocumentElement;
  for I := 0 to Root.ChildNodes.Count-1 do
  begin
    Node := Root.ChildNodes[I];
    if Node.Attributes['Id']=3 then
      Node.ChildNodes[2].NodeValue := 33333;
  end;
  Doc.SaveToFile('d:\jjw.xml');
end;

end.