2010-01-21 66 views
6

我在考慮救了我的應用程序設置爲XML,而不是使用註冊表,但我有一個很難理解和運用OmniXML應用程序的設置。如何使用OmniXML保存在XML文件

我知道你們在這裏使用,並建議更換OnmiXML所以我希望有人可以給我一些指點。

我已經習慣了使用TRegistry如果它不存在,創建一個新的關鍵,但我似乎無法找到任何OmniXML類似的選項。

基本上我希望做的是保存設置不同的XML層次,這樣的事情:

<ProgramName version="6"> 
    <profiles> 
    <profile name="Default"> 
     <Item ID="aa" Selected="0" /> 
     <Item ID="bb" Selected="1" /> 
    </profile> 
    </profiles> 
    <settings> 
    <CheckForUpdates>1</CheckForUpdates> 
    <CheckForUpdatesInterval>1</CheckForUpdatesInterval> 
    <ShowSplashScreen></ShowSplashScreen> 
    </settings> 
</ProgramName> 

現在,第一次運行程序時,我不會在XML文件,所以我需要創建所有的子水平。隨着TRegistry很容易,只需要調用打開項(pathtokey,真),如果它不存在的密鑰將被創建。 OmniXML有沒有類似的方法可以做同樣的事情? Someting like:

SetNodeStr('./settings/CheckForUpdates', True); 

如果它不存在,會創建「路徑」。

回答

10

使用OmniXML保存應用程序設置的簡單方法是使用OmniXMLPersistent單元。

OmniXML Sample Page說明你只需與公開的屬性定義的對象,並與TOmniXMLWriter類序列化對象的文件或字符串(與TOmniXMLReader類加載)

序列化支持對象嵌套的,所以你可以有複雜的結構,例如你的XML,可以通過這個對象表示:

type 
    TAppProfiles = class(TCollection) 
    ... 
    end; 

    TAppProfile = class(TCollectionItem) 
    ... 
    end; 

    TAppSettings = class(TPersistent) 
    private 
    FCheckForUpdates: Integer; 
    FCheckForUpdatesInterval: Integer; 
    FShowSplashScreen: Boolean; 
    published 
    property CheckForUpdates: Integer read FCheckForUpdates write FCheckForUpdates; 
    property CheckForUpdatesInterval: Integer read FCheckForUpdatesInterval write FCheckForUpdatesInterval; 
    property ShowSplashScreen: Boolean read FShowSplashScreen write FShowSplashScreen; 
    end; 

    TAppConfiguration = class(TPersistent) 
    private 
    FProfiles: TAppProfiles; 
    FSettings: TAppSettings; 
    published 
    property Profiles: TAppProfiles read FProfiles write FProfiles; 
    property Settings: TAppSettings read FSettings write FSettings; 
    end; 

//Declare an instance of your configuration object 
var 
    AppConf: TAppConfiguration; 

//Create it 
AppConf := TAppConfiguration.Create; 

//Serialize the object! 
TOmniXMLWriter.SaveToFile(AppConf, 'appname.xml', pfNodes, ofIndent); 

//And, of course, at the program start read the file into the object 
TOmniXMLReader.LoadFromFile(AppConf, 'appname.xml'); 

這一切..無需編寫XML yourse單行LF ...

如果你還是喜歡「手動」的方式,一起來看看在OmniXMLUtils單位或Fluent interface to OmniXML

啊..公開致謝(由普里莫茲Gabrijelcic的OmniXML作者寫的),以用於普里莫茲這個優秀的delphi庫!

+0

(普里莫茲這裏)只是爲了防止混淆 - OmniXML是寫的米·雷米克,我只是貢獻了一些小零件。 +1的答案 - 這正是我會寫的。 – gabr 2010-01-22 08:06:13

+0

謝謝paolorossi的答案和代碼。不幸的是,我還必須以編程方式讀取/寫入數百個值,因此對於該特定部分,我確實需要手動創建/讀取/刪除數據。任何人都知道如果可能自動創建先例節點,如果它們不存在?最後,感謝Miha Remec和Primoz Gabrijelcic分別爲OnmiXML和GpFluentXML。 – smartins 2010-01-22 10:33:50