保存/加载TObject(TPersistent)到XML

时间:2011-06-10 20:47:37

标签: delphi jedi tpersistent

大家。

我正在努力保存我的班级:

TA= class(TPersistent)
private
    FItems: TObjectList<TB>;

    FOnChanged: TNotifyEvent;
public
    constructor Create;
    destructor Destroy; override;
    ...
    procedure Delete(Index: Integer);
    procedure Clear;
    procedure SaveToFile(const FileName: string);
    ...
    property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
end;

使用以下代码进行归档:

var
  Storage: TJvAppXMLFileStorage;
begin
  Storage := TJvAppXMLFileStorage.Create(nil);
  try
    Storage.WritePersistent('', Self);
    Storage.Xml.SaveToFile(FileName);
  finally
    Storage.Free;
  end;

但文件总是空的。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

看起来TJvCustomAppStorage不支持属性中的泛型。代码不使用扩展RTTI,对TJvCustomAppStorage.GetPropCount的调用返回0。

这导致了另一个问题 - Are there Delphi object serialization libraries with support for Generics?

我的测试代码:

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes, Generics.Collections, JvAppXmlStorage;
type

  TA = class(TPersistent)
  private
    FItems: TObjectList<TPersistent>;
  public
    constructor Create;
  published
    property
      Items: TObjectList < TPersistent > read FItems write FItems;
  end;

  { TA }

constructor TA.Create;
begin
  FItems := TObjectList<TPersistent>.Create;
end;

var
  Storage: TJvAppXMLFileStorage;
  Test: TA;
begin
  Test := TA.Create;

  Test.Items.Add(TPersistent.Create);

  Storage := TJvAppXMLFileStorage.Create(nil);
  try
    Storage.WritePersistent('', Test);
    WriteLn(Storage.Xml.SaveToString);
    ReadLn;
  finally
    Storage.Free;
  end;

end.

答案 1 :(得分:1)

我不确定,但如果TJvAppXMLFileStorage使用RTTI,那么我认为您必须发布要保存/加载的属性。