Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good way to serialize Delphi object tree to XML--using RTTI and not custom code?

What's a good way to serialize a Delphi object tree to XML--using RTTI and not custom code?

I would have loved to find that this feature is already built into Delphi, but it doesn't seem to be.

I've found a few components (posted, below) that seem like they might perform this function. Have you used any of them or some other offering? Have you built your own? Am I missing something obvious, in Delphi?

like image 862
Mattias Andersson Avatar asked Dec 15 '08 16:12

Mattias Andersson


3 Answers

You can use the JVCL TJvAppXMLFileStorage component to serialize TPersistent derived classes.

uses
  JvAppXMLStorage;

var
  Storage: TJvAppXMLFileStorage;
begin
  Storage := TJvAppXMLFileStorage.Create(nil);
  try
    Storage.WritePersistent('', MyObject);
    Storage.Xml.SaveToFile('S:\TestFiles\Test.xml');

    Storage.Xml.LoadFromFile('S:\TestFiles\Test.xml');
    Storage.ReadPersistent('', MyObject);
  finally
    Storage.Free;
  end;
end;
like image 133
Andreas Hausladen Avatar answered Oct 23 '22 20:10

Andreas Hausladen


JVCL is one choice, but if you prefer a small, self-contained library, there's OmniXML (Mozilla Public License 1.1, http://www.omnixml.com/ ). I've used it successfully in several projects, and I find it the simplest XML library to use in Delphi. OmniXML comes with 'OmniXMLPersistent' unit, which does what you need via RTTI, just like the JVCL solution does.

// saving:
pers : TPersistent;
// SaveToFile is a class method, so no need to instantiate the object:
TOmniXMLWriter.SaveToFile( pers, 'd:\path\file.xml', pfAttributes, ofIndent );

pfAttributes means properties will be stored as attributes of XML elements; ofIndent will produce a nicely indented code for readability.

// loading:
TOmniXMLWriter.LoadFromFile( pers, 'd:\path\file.xml' ); 
like image 27
Marek Jedliński Avatar answered Oct 23 '22 20:10

Marek Jedliński


Simdesign's NativeXml

Link: http://www.simdesign.nl/xml.html

Licence: € 29,95

Quote: A native Delphi XML parser and writer. Unique feature: Store, read and create any TPersistent object to/from XML directly (see Example5). This is done by iterating through all of the objects' published properties by use of RTTI (runtime type information). This feature is only available for D5 and up.

like image 6
Mattias Andersson Avatar answered Oct 23 '22 19:10

Mattias Andersson