开发者

Is it possible to save a record to a XML file without saving the fields separately?

开发者 https://www.devze.com 2023-03-03 09:19 出处:网络
I have a big record which is consist of many fields with different types and also dynamic arrays. I want to save it to a file and then read it back. Imagine this simple record:

I have a big record which is consist of many fields with different types and also dynamic arrays. I want to save it to a file and then read it back. Imagine this simple record:

TCustomRecord = Record
   Field1 : array of integer;
   Field2  : Integer;
   Field3 : String;
end;

Normally I have to use something like this to save this record to a file:

var
   f : File of TCustomRecord;
   cr : TCustomeRecord;
 begin
   Write(f, cr);
 end;

But it doesn't work because of dynamic array and string type.

So the question is:

Is there a way to save (export) it to a TXMLDocument without going through all the fields? (I mean adding f开发者_运维问答ield-by-field using addChild())


Your XML library obviously needs to know what the fields' values are, or else it cannot serialize them, so you're going to have to go "through all the fields" at some point. Whether you do it manually or have some way of traversing your data structure automatically (like with RTTI) makes no difference. Something has to look at all the fields.


I'll cautiously say "No", although I have no idea what you mean by "going through all the fields".

Another answer links to a workable way of iterating the fields in your record using RTTI. Then you must make sure your records are not going to use any type that your RTTI-iterator code doesn't understand, or it won't get saved.

As far as "not having to call AddChild yourself", you could simply store everything in XML attributes, without any child nodes. I don't know if you know this, but there is not only one way to map fields in a record to possible XML content that could result.

Here's an example record:

TMyData = record
           Name:String;
           Age:Integer;
           Money:Double;
end;

If you wanted to not call AddChild at all you could just write to the attributes, producing one entity like this:

  <MyData  Name="Warren" Age="48" Money="100.00"   />

There's nobody saying you even HAVE to use child nodes:

  <MyData> 
    <Name>Warren</Name>
    <Age>48</Age>
    <Money>100.00<Money/>
  </MyData>

So it seems to me you're avoiding the fact that XML provides you lots of ways to do them, and that an MSXML DOM like API gives you more than one way to map any record to a file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号