{This code shows how to use TXMLDocument to save and restore configuration
settings in a XML document. The public methods works the same as a TIniFile.
There is not mutch comment in the code because it is self explaining
and small. Hope this benefit other persons. It is only tested in D7 pro.}
constructor TXMLConfig.Create(const FileName: string); begin
inherited Create;
FBackup := True;
FFileName := FileName;
FXMLDoc := TXMLDocument.Create(Application);
FXMLDoc.Options := [doNodeAutoIndent]; if FileExists(FFileName) then FXMLDoc.LoadFromFile(FFileName) else
begin FXMLDoc.Active := True;
FXMLDoc.AddChild('Configuration'); end; end;
constructor TXMLConfig.Create; begin Create(ChangeFileExt(Application.Exename, '_cfg.xml')); end;
destructor TXMLConfig.Destroy; begin Save;
FXMLDoc.Destroy; inherited; end;
function TXMLConfig.GetVersion: string; begin Result := '1.00'; end;
function TXMLConfig.ReadBoolean(const Section, Key: string; default: Boolean): Boolean; begin Result := Boolean(ReadInteger(Section, Key, Integer(default))); end;
function TXMLConfig.ReadInteger(const Section, Key: string; default: Integer): Integer; begin Result := StrToInt(ReadString(Section, Key, IntToStr(default))); end;
function TXMLConfig.ReadString(const Section, Key, default: string): string; var Node: IXMLNode; begin Node := FXMLDoc.DocumentElement.ChildNodes.FindNode(Section); if Assigned(Node) and Node.HasAttribute(Key) then Result := Node.Attributes[Key] else Result := default; end;
procedure TXMLConfig.Save; begin
if not FModified then Exit; if FBackup then
procedure TXMLConfig.WriteString(const Section, Key, Value: string); var Node: IXMLNode; begin
if ReadString(Section, Key, '') = Value then Exit;
Node := FXMLDoc.DocumentElement.ChildNodes.FindNode(Section); if not Assigned(Node) then Node := FXMLDoc.DocumentElement.AddChild(Section);
Node.Attributes[Key] := Value;
FModified := True; end;