你可以继承自TPersistent,然后使用TJvAppXMLFileStorage (
JVCL) 组件来序列化TAlarm类。
保存对象:
uses
JvAppXMLStorage;
Procedure SaveMyObject(MyAlarm : TAlarm)
var
MyStore: TJvAppXMLFileStorage;
begin
MyStore:= TJvAppXMLFileStorage.Create(nil);
try
MyStore.WritePersistent('', MyAlarm);
MyStore.Xml.SaveToFile('C:\MyAlarm.xml');
finally
MyStore.Free;
end;
end;
恢复一个对象
uses
JvAppXMLStorage;
Procedure LoadMyObject(MyAlarm : TAlarm)
var
MyStore: TJvAppXMLFileStorage;
begin
MyStore:= TJvAppXMLFileStorage.Create(nil);
try
MyStore.FileName:='C:\MyAlarm.xml';
MyStore.Xml.LoadFromFile('C:\MyAlarm.xml');
MyStore.ReadPersistent('', MyAlarm);
finally
MyStore.Free;
end;
end;
更新
如果您需要将多个对象持久化到XML文件中,您必须为WritePersistent和ReadPersistent方法分配一个路径(唯一标识符)。
请参考以下示例:
多个持久化
Procedure SaveMyObjects(MyObjects : Array of TComponent);
var
MyStore: TJvAppXMLFileStorage;
i : integer;
begin
MyStore:= TJvAppXMLFileStorage.Create(nil);
try
for i := Low(MyObjects) to High(MyObjects) do
MyStore.WritePersistent(MyObjects[i].Name, MyObjects[i]);
MyStore.Xml.SaveToFile('C:\Tools\MyAlarm.xml');
finally
MyStore.Free;
end;
end;
保存组件
SaveMyObjects([Button1,Button2,Edit1,Edit2]);
多重加载
Procedure LoadMyObjects(MyObjects:Array of TComponent);
var
MyStore : TJvAppXMLFileStorage;
i : integer;
begin
MyStore:= TJvAppXMLFileStorage.Create(nil);
try
MyStore.FileName:='C:\Tools\MyAlarm.xml';
MyStore.Xml.LoadFromFile('C:\Tools\MyAlarm.xml');
for i := Low(MyObjects) to High(MyObjects) do
MyStore.ReadPersistent(MyObjects[i].Name, MyObjects[i]);
finally
MyStore.Free;
end;
end;
恢复属性
LoadMyObjects([Button1,Button2,Edit1,Edit2]);
加载的另一种选择
Procedure LoadMyObjectById(Id:String;MyObject:TComponent);
var
MyStore : TJvAppXMLFileStorage;
i : integer;
begin
MyStore:= TJvAppXMLFileStorage.Create(nil);
try
MyStore.FileName:='C:\Tools\MyAlarm.xml';
MyStore.Xml.LoadFromFile('C:\Tools\MyAlarm.xml');
MyStore.ReadPersistent(id, MyObject);
finally
MyStore.Free;
end;
end;
你必须以这种方式运行它。
LoadMyObjectById(Button1.Name,Button1)
我希望这个例子对你有所帮助 ; )