NativeXml Help
Example C: Event driven handling
This example shows how NativeXml can be used in a SAX-like manner, reading a file sequentially and generating events whenever a node is initiated and loaded.

Add a TButton (Button3) and a TMemo (Memo1) to your form, then include NativeXml in the uses clause. Next, type the code below in the TButton.OnClick event handler.

procedure TForm1.Button3Click(Sender: TObject);
var
  ADoc: TNativeXml;
begin
  Memo1.Lines.Clear;
  ADoc := TNativeXml.Create;
  try
    ADoc.OnNodeNew    := DoNodeNew;
    ADoc.OnNodeLoaded := DoNodeLoaded;
    ADoc.LoadFromFile(Edit1.Text);
  finally
    ADoc.Free;
  end;
end;
Type the code below in new TForm1 procedures:

function TForm1.Indent(ACount: integer): string;
begin
  while ACount > 0 do begin
    Result := Result + '  ';
    dec(ACount);
  end;
end;

procedure TForm1.DoNodeNew(Sender: TObject; Node: TXmlNode);
begin
  Memo1.Lines.Add(Format('New   : %sName=%s', [Indent(Node.TreeDepth), Node.Name]));
end;

procedure TForm1.DoNodeLoaded(Sender: TObject; Node: TXmlNode);
begin
  Memo1.Lines.Add(Format('Loaded: %sName=%s, Value=%s', [Indent(Node.TreeDepth), Node.Name, Node.ValueAsString]));
end;
Whenever a node is found, the OnNodeNew event is fired, and whenever a node is completely loaded, the OnNodeLoaded event is fired.

If you do not want to keep a complete copy of the XML file in memory, for example for huge XML files, you can directly remove the node and free its memory. In that case, add the following code to the OnNodeLoaded event:

procedure TForm1.DoNodeLoaded(Sender: TObject; Node: TXmlNode);
begin
  Memo1.Lines.Add(Format('Loaded: Name=%s, Value=%s', [Node.Name, Node.ValueAsString]));
  if Node.TreeDepth > 0 then begin
    Memo1.Lines.Add(Format('Deleted: Name=%s', [Node.Name]));
    Node.Delete;
  end;
end;