xmlconf/ru

From Lazarus wiki
Jump to navigationJump to search

English (en) русский (ru)

Модуль XMLConf предоставляет компонент TXMLConfig. Он использует объект TXMLDocument для чтения и записи XML-файла, но происходит непосредственно от TComponent.

Отказ от ответственности

Эта документация не является официальной, она основана на обычном процессе 1) изучения исходного кода; 2) экспериментирования; 3) размышлений: «Интересно, это ли имел в виду автор?»

Свойства и процедуры

property Filename
property Filename: String (published)

Имя XML-файла. Установка другого имени файла:

  • Очищает текущий xml-файл.
  • Освобождает объект xmldocument
  • Если Filename существует и StartEmpty имеет значение false:
    • Новый xmldocument создается путем чтения файла, который должен иметь тот же root элемент, что и RootName, в противном случае возникает исключение.
    • В противном случае создается новый объект xmldocument с корневым элементом RootName

Я не проверял это экспериментально, но похоже, что пустой xmldocument создается (в памяти) при создании компонента, и это можно изменить. Однако его нельзя сохранить, пока у него не будет имени файла - нет имени файла по умолчанию - следовательно, все изменения неизбежно будут потеряны, когда имя файла будет установлено.

property StartEmpty
property StartEmpty: Boolean (published)

Определяет, читается ли существующий xmlfile из Filename.

  • По умолчанию false - читается существующий файл.
property RootName
property RootName: DOMString (published)

Имя root элемента в файле. Должно соответствовать значению в файле при чтении существующего файла.

  • По умолчанию - 'CONFIG'. Проще всего оставить это в покое, если у вас нет веской причины это менять.
procedure Flush
procedure Flush (public)

Записывает файл xml - если задано имя файла.

procedure Clear
procedure Clear (public)

Воссоздает xmldocument как пустой документ.

constructor Create
constructor Create(AOwner: TComponent) (public)
destructor Destroy
destructor Destroy (public)

Работа с ключами и путями

XMLConfig поддерживает «стек» путей (как массив широких строк). Общий путь к элементу может быть

 <rootName>/key1/key2/key3/key4/value="some_value".  

Это появится в файле в виде

<CONFIG>
  <key1>
    <key2>
      <key3>
        <key4 value="some_value"/>
      </key3>
    </key2>
  </key1>
</CONFIG>

(пренебрегая любыми другими элементами). Однако стек путей может содержать пути, а не только узлы, поэтому он может состоять из четырех элементов глубиной key1;key2; key3;key4, но точно так же только два элемента, как key1/key2;key3/key4, или три элемента, как key1;key2/key3;key4.

Кроме того, при чтении или установке значения можно указать полный путь, так что можно полностью игнорировать «стек» пути и указать полный путь (после RootName) для каждого значения. У каждого значения есть эффективный путь, а стек путей - это просто удобный способ добраться до конкретного эффективного пути.

procedure OpenKey(const aPath: WideString) (public)

procedure OpenKey(const aPath: WideString) (public) "Pushes" aPath onto the stack. If the effective path was <RootName>/key1, and aPath = key2/key3, after the call to OpenKey, the effective path is <RootName>/key1/key2/key3.

procedure CloseKey (public)

"Pops" the top path off the stack. Note that this is the last entered path, NOT the top element. Thus after the OpenKey example above followed by a CloseKey call, the stack reverts to <RootName>/key1, not <RootName>/key1/key2

procedure ResetKey (public)

Completely clears the stack. The effetive path reverts to <RootName>

Setting, Getting and Deleting Values

All values are actually read and written as strings, with other overloaded types providing defined 'AsString' translations.

function GetValue(const APath: WideString; const ADefault: WideString): WideString (public)
procedure SetValue(const APath: WideString; const AValue: WideString) (public)

Sets or Gets a string value from RootName/Effective_path_from_stack/APath. The path is created if it does not exist on Setting, and ADefault is returned if the path does not exist on Getting.

function GetValue(const APath: WideString; ADefault: Integer): Integer; (public)
procedure SetValue(const APath: WideString; AValue: Integer); (public)

The integer values are converted to/from strings using IntToStr and strToIntDef

function GetValue(const APath: WideString; ADefault: Boolean): Boolean; (public)
procedure SetValue(const APath: WideString; AValue: Boolean); (public)

The boolean values are stored as "True" or "False".

Warning - some other FCL/LCL XML components (eg those descended from TCustomPropertyStorage, such as TXMLPropStorage) store booleans using integer values, despite using XMLConifg as the storage component. This is, of course, only a problem if you use the same files from both components, or switch from one to the other during development, as I did.

procedure SetDeleteValue(const APath: WideString; const AValue, DefValue: WideString); (public)
procedure SetDeleteValue(const APath: WideString; AValue, DefValue: Integer); (public)
procedure SetDeleteValue(const APath: WideString; AValue, DefValue: Boolean); (public)

If AValue = DefValue, the element is deleted. Otherwise, it is set to AValue.

I have not used this, but presumably could be used to store eg values of properties with well defined defaults only when they were different from the defaults.

procedure DeletePath(const APath: WideString); (public)

Deletes everything beyond path APath

procedure DeleteValue(const APath: WideString); (public)

Deletes a value specified by APath. If APath does not specify a value , it does nothing

property Modified: Boolean read FModified; (public)

Allows you to see if the xmldocument has been modified, and hence, needs to be flushed. However, flush does nothing if the document is not modified, so it is easier just to call flush anyway.

Example

The following sequence of instructions:

  XmlConfig1.Filename := FILE_NAME ;        // reads the file if it already exists, but...
  XmlConfig1.Clear ;                        // if the file already exists, clear the data, we want to start from scratch
  XmlConfig1.SetValue ('L1/L2/L3', '333') ; // add a few data
  XmlConfig1.SetValue ('L1/L2/L4', '44') ;
  XmlConfig1.SetValue ('L1/L2/L3', '33') ;  // this will overwrite the previous value
  XmlConfig1.OpenKey  ('L1/L2') ;           // from now on, all keys will be relative to L1/L2
  XmlConfig1.SetValue ('Lm', 'mm') ;        // these will be added in L1/L2
  XmlConfig1.SetValue ('Lm/Ln', 'nn') ;
  XmlConfig1.SetValue ('/Lx/Ly', 'yy') ;    // but because of the initial "/", this will be added to the root
  XmlConfig1.CloseKey ;
  XmlConfig1.SetValue ('L6/L7', '77') ;     // L6 will be deleted
  XmlConfig1.SetValue ('L9', '99') ;
  XmlConfig1.SetValue ('L9/L99', '9999') ;  // the previous L9 was an attibute, this one will be a node
  XmlConfig1.DeletePath ('L6') ;
  XmlConfig1.Flush ;

will give this XML:

  <?xml version="1.0" encoding="utf-8"?>
  <CONFIG L9="99">
    <L1>
      <L2 L3="33" L4="44" Lm="mm">
        <Lm Ln="nn"/>
      </L2>
    </L1>
    <Lx Ly="yy"/>
    <L9 L99="9999"/>
  </CONFIG>

Note that the last item in the aPath parameter for SetValue is actually an attribute: XmlConfig1.SetValue ('L1/L2/L3', '333') actually sets attribute L3 for element L1/L2.


See also

  • XMLConf/TXMLConf is provided by the fcl-xml package.