用 JVCL 的控件TJvAppXMLFileStorage来序列化对象为 XML

46 views
Skip to first unread message

电脑玩家

unread,
Oct 27, 2009, 11:30:35 PM10/27/09
to 挨踢技术
可以序列化 TPersistent 子类的对象为 XML,当然也可以反序列化回来。
还可以把很多个对象放到一个 TList 里,直接序列化这个 TList。也就是说可以把对象列表输出为 XML。


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Forms,
Dialogs, InvokeRegistry, StdCtrls, JvComponentBase, JvAppStorage,
JvAppXMLStorage;

type
TMyCard = class(TComponent)
private
FMyName: string;
FAge: Integer;
published
property MyName: string read FMyName write FMyName;
property Age: Integer read FAge write FAge;
end;

TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
JvAppXMLFileStorage1: TJvAppXMLFileStorage;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FList: TList;
FList2: TList;

function DoCreateItem(Sender: TJvCustomAppStorage; const Path:
string; Index: Integer): TPersistent;
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
C: TMyCard;
S: string;
i: Integer;
begin
C := TMyCard.Create(nil);
C.Name := 'MyCard_1';
C.MyName := 'pcplayer';
C.Age := 25;

FList.Add(C);

C := TMyCard.Create(nil);
C.Name := 'MyCard_1';
C.MyName := 'pcplayer99';
C.Age := 28;
FList.Add(C);

C := TMyCard.Create(nil);
C.Name := 'MyCard_1';
C.MyName := '王大山';
C.Age := 30;
FList.Add(C);


//JvAppXMLFileStorage1.WritePersistent('', C);
JvAppXMLFileStorage1.WriteObjectList('', FList, '');
S := JvAppXMLFileStorage1.Xml.XMLData;
Memo1.Lines.Add(S);

JvAppXMLFileStorage1.ReadObjectList('', FList2, DoCreateItem, True,
'');


for i := 0 to FList2.Count -1 do
begin
C := TMyCard(FList2.Items[i]);
S := C.MyName;
Memo1.Lines.Add(S);
end;
end;

function TForm1.DoCreateItem(Sender: TJvCustomAppStorage;
const Path: string; Index: Integer): TPersistent;
begin
Result := TMyCard.Create(nil);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
FList := TList.Create;
FList2 := TList.Create;
end;

end.
Reply all
Reply to author
Forward
0 new messages