草庐IT

xml 中的 xml 示例/应用程序设置

coder 2024-06-25 原文

谁能帮助我学习如何使用 XML。作为测试,我想使用 XML 而不是 INI 文件来保存程序设置。

谢谢

最佳答案

Rigo,你可以使用 IXMLDocument接口(interface)或 TXMLDocument对象与 XML 文档进行交互。

您可以查看这些链接以获取有关 XML 和 Delphi 的更多信息

查看此示例代码,了解使用 IXMLDocument 进行 xml 管理的基础知识界面。

program Delphi_XmlSaveSettings;

{$APPTYPE CONSOLE}
uses
  ActiveX,
  SysUtils,
  XmlDoc,
  XmlIntf;
//this class mimic the basics functionalities of an TIniFile
//you can improve a lot the code adding exception handling and more methods for specifics tasks.
type
  TXMLSettings = class 
  private
    FFileName: string;
    FXMLDoc: IXMLDocument; //Main XMLObject
  public
    constructor Create(const FileName: string); overload;
    destructor  Destroy; override;
    function    ReadString(const Section, Key, default: string): string;
    procedure   WriteString(const Section, Key, Value: string);
    function    ReadInteger(const Section, Key: string; default: Integer): Integer;
    procedure   WriteInteger(const Section, Key: string; Value: Integer);
    function    ReadBoolean(const Section, Key: string; default: Boolean): Boolean;
    procedure   WriteBoolean(const Section, Key: string; Value: Boolean);
    function    ReadDouble(const Section, Key: string; default: Double): Double;
    procedure   WriteDouble(const Section, Key: string; Value: Double);
    function    ReadDateTime(const Section, Key: string; default: TDatetime): TDateTime;
    procedure   WriteDatetime(const Section, Key: string; Value: TDatetime);
    function    ReadDate(const Section, Key: string; default: TDatetime): TDateTime;
    procedure   WriteDate(const Section, Key: string; Value: TDatetime);
    procedure   Save;
  end;



constructor TXMLSettings.Create(const FileName: string);
begin
  inherited Create;
  FFileName       := FileName;
  FXMLDoc         := NewXMLDocument; //Create  aNew instance of a XML Document
  FXMLDoc.Encoding:= 'UTF-8'; //Set the encoding
  FXMLDoc.Options := [doNodeAutoIndent];//optional, is used to indent the Xml document

  if FileExists(FFileName) then
    FXMLDoc.LoadFromFile(FFileName)
  else
    FXMLDoc.AddChild('Root'); //Create the root Node
end;


destructor TXMLSettings.Destroy;
begin
  Save;
  inherited;
end;

function TXMLSettings.ReadBoolean(const Section, Key: string; default: Boolean): Boolean;
begin
  Result := Boolean(ReadInteger(Section, Key, Integer(default)));
end;

function TXMLSettings.ReadDate(const Section, Key: string; default: TDatetime): TDateTime;
begin
  Result := StrToDate(ReadString(Section, Key, DateToStr(default)));
end;

function TXMLSettings.ReadDateTime(const Section, Key: string; default: TDatetime): TDateTime;
begin
  Result := StrToDateTime(ReadString(Section, Key, DateTimeToStr(default)));
end;

function TXMLSettings.ReadDouble(const Section, Key: string;  default: Double): Double;
begin
  Result := StrToFloat(ReadString(Section, Key, FloatToStr(default)));
end;

function TXMLSettings.ReadInteger(const Section, Key: string; default: Integer): Integer;
begin
  Result := StrToInt(ReadString(Section, Key, IntToStr(default)));
end;

function TXMLSettings.ReadString(const Section, Key, default: string): string; 
var
  XMLNode: IXMLNode;
begin
  XMLNode := FXMLDoc.DocumentElement.ChildNodes.FindNode(Section);
  if Assigned(XMLNode) and XMLNode.HasAttribute(Key) then //Check if exist the Key
    Result := XMLNode.Attributes[Key]
  else
    Result := default;
end;

procedure TXMLSettings.Save;
begin
  FXMLDoc.SaveToFile(FFileName);
end;

procedure TXMLSettings.WriteBoolean(const Section, Key: string; Value: Boolean);
begin
  WriteInteger(Section, Key, Integer(Value));
end;

procedure TXMLSettings.WriteDate(const Section, Key: string; Value: TDatetime);
begin
  WriteString(Section, Key, DateToStr(Value));
end;

procedure TXMLSettings.WriteDatetime(const Section, Key: string;  Value: TDatetime);
begin
  WriteString(Section, Key, DateTimeToStr(Value));
end;

procedure TXMLSettings.WriteDouble(const Section, Key: string; Value: Double);
begin
  WriteString(Section, Key, FloatToStr(Value));
end;

procedure TXMLSettings.WriteInteger(const Section, Key: string; Value: Integer);
begin
  WriteString(Section, Key, IntToStr(Value));
end;

procedure TXMLSettings.WriteString(const Section, Key, Value: string);
var
  XMLNode: IXMLNode;
begin
  XMLNode := FXMLDoc.DocumentElement.ChildNodes.FindNode(Section);
  if not Assigned(XMLNode) then
  XMLNode := FXMLDoc.DocumentElement.AddChild(Section);
  XMLNode.Attributes[Key] := Value;
end;


Procedure SaveSettings; //Store the settings
Var
  AppSettings :  TXMLSettings;
begin
  AppSettings:=TXMLSettings.Create(ExtractFilePath(ParamStr(0))+'MySettings.xml');
  try
   AppSettings.WriteString('Server','Type','SQLServer');
   AppSettings.WriteString('Server','User','root');
   AppSettings.WriteInteger('Server','port',1433);
   AppSettings.WriteString('Server','IP','192.168.1.1');
   AppSettings.WriteString('Server','Database','Prod');
   AppSettings.WriteBoolean('Server','WindowsAuth',False);
   AppSettings.WriteDouble('Server','Latency',25.90892);
   AppSettings.WriteDatetime('Server','LastAccess',Now);
   AppSettings.WriteDate('Server','ActualDate',Now);
   AppSettings.Save;
  finally
  AppSettings.Free;
  end;
  Writeln('Settings Saved');
end;


Procedure ShowSettings;//Read the settings
Var
  AppSettings :  TXMLSettings;
begin
  AppSettings:=TXMLSettings.Create(ExtractFilePath(ParamStr(0))+'MySettings.xml');
  try
   Writeln(Format('Type         %s',[AppSettings.ReadString('Server','Type','')]));
   Writeln(Format('Port         %d',[AppSettings.ReadInteger('Server','port',0)]));
   Writeln(Format('IP           %s',[AppSettings.ReadString('Server','IP','')]));
   Writeln(Format('Database     %s',[AppSettings.ReadString('Server','Database','')]));
   Writeln(Format('WindowsAuth  %s',[BoolToStr(AppSettings.ReadBoolean('Server','WindowsAuth',True),True)]));
   Writeln(Format('Latency      %g',[AppSettings.ReadDouble('Server','Latency',0)]));
   Writeln(Format('LastAccess   %s',[DateTimeToStr(AppSettings.ReadDateTime('Server','LastAccess',Now-1))]));
   Writeln(Format('ActualDate   %s',[DateToStr(AppSettings.ReadDate('Server','ActualDate',Now-1))]));
  finally
  AppSettings.Free;
  end;
end;

begin
  try
    CoInitialize(nil); //only necesary in console applications
    try
      SaveSettings; //Save the sample settings
      ShowSettings; //Read the stored settings
      Readln;
    finally
    CoUninitialize; //only necesary in console applications
    end;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.

关于xml 中的 xml 示例/应用程序设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3687116/

有关xml 中的 xml 示例/应用程序设置的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  4. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  5. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  6. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  7. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  8. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  9. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  10. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

随机推荐