边学边用,利用RTTI把Record的值转成XmlNode的属性,留下纪号,方便以后作用。
Procedure RecordToXMLNode(RecordType, aRecord: Pointer; var aXMLNode: TXMLNode);
var
RTX: TRttiContext;
RT: TRttiType;
RF: TRttiField;
begin
RTX := TRttiContext.Create;
RT := RTX.GetType(RecordType);
for RF in RT.AsRecord.GetFields do
begin
case RF.GetValue(aRecord).Kind of
tkInteger:
aXMLNode.WriteAttributeInteger(RF.Name, RF.GetValue(aRecord).AsInteger);
tkInt64:
aXMLNode.WriteAttributeInt64(RF.Name, RF.GetValue(aRecord).AsInt64);
tkstring:
aXMLNode.WriteAttributeString(RF.Name, RF.GetValue(aRecord).AsString);
tkUString:
aXMLNode.WriteAttributeUnicodeString(RF.Name, RF.GetValue(aRecord).AsString);
end;
end;
RTX.Free;
end;
procedure XmlNodeToRecord(RecordType, aRecord: Pointer; aXMLNode: TXMLNode);
var
RTX: TRttiContext;
RT: TRttiType;
RF: TRttiField;
begin
RTX := TRttiContext.Create;
RT := RTX.GetType(RecordType);
for RF in RT.AsRecord.GetFields do
begin
// RF.FieldType.TypeKind
case RF.GetValue(aRecord).Kind of
tkInteger:
RF.SetValue(aRecord, aXMLNode.ReadAttributeInteger(RF.Name, 0));
tkInt64:
RF.SetValue(aRecord, aXMLNode.ReadAttributeInt64(RF.Name, 0));
tkstring:
RF.SetValue(aRecord, aXMLNode.ReadAttributeString(RF.Name, ''));
end;
end;
RTX.Free;
end;