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

北城以北 提交于 2019-11-29 21:06:36

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;

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' ); 

DragonSoft's XML Class Serializer

Link: http://www.dragonsoft.us/delphi_vcl.php

Licence: Licensed under the Mozilla Public Licence ("MPL") version 1.1

Quote: Allows to serialize/deserialize VCL Objects/Components via XML. Store/restore state of the object (published properties). Special classes support - TStrings, TCollection, TPicture. Full process control.

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.

JVCL's TJvTranslator.ComponentToXML

Link: http://sourceforge.net/project/showfiles.php?group_id=45786&package_id=42327

Licence: Licensed under the Mozilla Public Licence ("MPL") version 1.1

Observation: Seems to do recursive serialization, but the fact that it is clearly intended for "Translation" gives me pause.

I've made a serializer for D2006 using SOAP XML: http://jankajanos.spaces.live.com/blog/cns!C3E2695FC6F7B0A4!791.entry

But there is a generic edition for D2009 too.

I've uploaded a new version. It contains english comments: http://janosjanka.spaces.live.com/blog/cns!E5C994C03FC0E370!181.entry In addition, it can deserialize an object through pre-registred class types. This is a very useful thing because you can deserialize objects without know types.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!