【发布时间】:2011-06-10 17:50:43
【问题描述】:
我正在尝试使用 Delphi XE 或更高版本中增强的 RTTI 功能来读取对象并将对象写入 XML。到目前为止,我在整数、浮点数、字符串、枚举类型、集合和类方面取得了成功,但无法正确输出或读取记录。问题似乎是获取一个指向记录属性的实例(指针)。
//Outputs Properties To XML
procedure TMyBase.SaveToXML(node: TJclSimpleXMLElem);
var
child , subchild : TjclSimpleXMLElem ;
FContext : TRttiContext ;
FType : TRttiType ;
FProp : TRttiProperty ;
Value : TValue ;
MyObj : TMyBase ;
FField : TRttiField ;
FRecord : TRttiRecordType ;
Data : TValue ;
begin
FContext := TRttiContext.Create ;
FType := FContext.GetType ( self.ClassType ) ;
Child := node.Items.Add ( ClassName ) ;
for FProp in FType.GetProperties do begin
if FProp.IsWritable then begin
case FProp.PropertyType.TypeKind of
tkClass : begin
MyObj := TMyBase ( FProp.GetValue ( self ).AsObject ) ;
MyObj.SaveClass ( Child.Items.Add ( FProp.Name ) , FContext ) ;
end ;
tkRecord : begin
subchild := Child.Items.Add ( FProp.Name ) ;
FRecord := FContext.GetType(FProp.GetValue(self).TypeInfo).AsRecord ;
for FField in FRecord.GetFields do begin
>>> self is not the correct instance <<<
Value := FField.GetValue ( self ) ;
subchild.Items.Add ( FField.Name ).Value := Value.ToString ;
end;
end ;
else begin
Value := FProp.GetValue(self) ;
Child.Items.Add ( FProp.Name ).Value := Value.ToString ;
end;
end;
end ;
end ;
FContext.Free ;
end;
我怀疑如果我能弄清楚如何获取这些值,那么设置它们应该不是问题。然后到数组上,天哪!
更新:请参阅below。 (迁移为单独的答案以提高可见性)。
【问题讨论】:
-
Delphi 的哪个版本?
-
您是否有任何特殊原因要保存“记录”而不是“类”?如果否,则检查 OmniXML,它具有保存和加载 TPersistent 后代到/从 *.XML 文件的能力。 omnixml.com
-
谢谢 Dorin 我会看看的。我考虑过限制支持的类型,但由于现有应用程序已经使用了大量记录,我想涵盖记录和记录数组。