Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
Serialize / Deserialize Hashtable to/from XML
Demonstrates how to seralize / deserialize a Hashtable to/from XML.Note: This example requires Chilkat v9.5.0.64 or later.
Chilkat Pascal (Lazarus/Delphi) Downloads
program ChilkatDemo;
// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils,
CkDllLoader,
Chilkat.StringTable,
Chilkat.StringBuilder,
Chilkat.Hashtable;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
hashTab: THashtable;
sb: TStringBuilder;
hashTab2: THashtable;
sTable: TStringTable;
i: Integer;
numKeys: Integer;
key: string;
begin
// Note: This example requires Chilkat v9.5.0.64 or later.
// Add some entries to a hashtable.
hashTab := THashtable.Create;
hashTab.AddStr('aaa','111');
hashTab.AddStr('bbb','222');
hashTab.AddStr('ccc','333');
// Serialize to XML
sb := TStringBuilder.Create;
hashTab.ToXmlSb(sb);
WriteLn(sb.GetAsString());
WriteLn('---');
// The output is as follows. Each hash table entry
// is contained in an "e" node. The entry's key
// is in the "k" node, and the value in the "v" node.
// <?xml version="1.0" encoding="utf8-8"?>
// <hashtable>
// <e><k>aaa</k><v>111</v></e>
// <e><k>bbb</k><v>222</v></e>
// <e><k>ccc</k><v>333</v></e>
// </hashtable>
//
// Now load (deserialize) into a new hash table.
hashTab2 := THashtable.Create;
hashTab2.AddFromXmlSb(sb);
// Get the hash table keys, and lookup each (to show
// that the hash table was correctly deserialized).
// The GetKeys method can return the keys in any order.
sTable := TStringTable.Create;
hashTab2.GetKeys(sTable);
i := 0;
numKeys := sTable.Count;
while i < numKeys do
begin
key := sTable.StringAt(i);
WriteLn(key + ': ' + hashTab2.LookupStr(key));
i := i + 1;
end;
hashTab.Free;
sb.Free;
hashTab2.Free;
sTable.Free;
end;
// ---------------------------------------------------------------------------
begin
try
RunDemo;
except
on E: Exception do
WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
end;
WriteLn;
{$IFDEF MSWINDOWS}
WriteLn('Press Enter to exit...');
ReadLn;
{$ENDIF}
end.