2
\$\begingroup\$

I have created this unit containing a class derived from TXmlIniFile. This class uses the common TCustomInifile methods to write to and read from an XML file. It comes from an idea of Chris Rolliston from his book "Delphi XE2 Foundations" (which I warmly recommend):

unit PAXMLIniFile;

interface

uses
  System.SysUtils,
  System.IniFiles,
  Xml.XmlDoc,
  Xml.XMLIntf,
  Xml.XMLIniFile;

type
  TMyStandaloneXmlIniFile = class(TXmlIniFile)
  strict private
    FDocument: IXMLDocument;
    FFileName: string;
  public
    constructor Create(const AFileName: string);
    procedure UpdateFile; override;
  end;

implementation

constructor TMyStandaloneXmlIniFile.Create(const AFileName: string);
begin
  if FileExists(AFileName) then
    FDocument := LoadXMLDocument(AFileName)
  else
  begin
    FDocument := NewXMLDocument;
    FDocument.Options := FDocument.Options + [doNodeAutoIndent];
  end;
  if FDocument.DocumentElement = nil then
    FDocument.DocumentElement := FDocument.CreateNode('Sections');
  TCustomIniFile(Self).Create(AFileName); 
  FFileName := AFileName;
  inherited Create(FDocument.DocumentElement);
end;

procedure TMyStandaloneXmlIniFile.UpdateFile;
begin
  FDocument.SaveToFile(FFileName);
end;

end.

Usage - Here is the test program:

program XMLTest;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, PAXMLIniFile, Winapi.ActiveX;

var
  MyStandaloneXmlIniFile: TMyStandaloneXmlIniFile;
  MyXmlFile: string;

begin
  try
    CoInitialize(nil);
    MyXmlFile := ChangeFileExt(ParamStr(0), '.xml');
    MyStandaloneXmlIniFile := TMyStandaloneXmlIniFile.Create(MyXmlFile);
    try
      MyStandaloneXmlIniFile.WriteString('Section1', 'Ident1', 'Value1');
      MyStandaloneXmlIniFile.UpdateFile;
    finally
      MyStandaloneXmlIniFile.Free;
    end;
    CoUninitialize;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Does anybody find any flaws in the class or in the usage?

\$\endgroup\$
1
  • \$\begingroup\$ When the AFileName parameter passed to the constructor is empty then it should raise an exception. This would make the code more secure, as an error could be detected earlier. What do you think? \$\endgroup\$ – user1580348 Feb 24 '15 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.