[Lazarus] XML and memory loss

Sergei Gorelkin sergei_gorelkin at mail.ru
Thu Oct 9 12:01:16 CEST 2008


Bart wrote:
> 
> Then how can I free those TDOMNodeList objects? I.o.w. how can I get 
> access to them?
> 
You just put them into a variable and later call Free:

var
   Nodes: TDOMNodeList;
...
Nodes := MyNode.ChildNodes;
writeln(Nodes[0].NodeName);
...
Nodes.Free

> I tried that, and it wordk like a charm.
> However can I use that approach if I want to create more complex XML files?
> 
> Eventually I want someting like this:
> <?xml version="1.0"?>
> <root>
>   <version>foo bar version 0.0.1</version>
>   <children>
>     <child id="0001">
>       <foo>Bart</foo>
>       <bar>me, myself and I</bar>
>     </child>
>     <child id="0002">
>       <foo>Bob</foo>
>       <bar>blah</bar>
>     </child>
>  <children/>
> </root>
> 
In general, any tree can be built using only the AppendChild method. 
Just put necessary nodes in variables. Here is your example:

var
   doc: TXMLDocument;
   root, tmp, children, foo, bar: TDOMNode;
begin
   doc := TXMLDocument.Create;
   root := doc.CreateElement('root');
   doc.AppendChild(root);
   tmp := doc.CreateElement('version');
   tmp.AppendChild(doc.CreateTextNode('foo bar version 0.0.1'));
   root.AppendChild(tmp);
   children := doc.CreateElement('children');
   root.AppendChild(children);
   // first child
   tmp := doc.CreateElement('child');
   tmp['id'] := '0001';
   foo := doc.CreateElement('foo');
   foo.AppendChild(doc.CreateTextNode('Bart'));
   tmp.AppendChild(foo);
   bar := doc.CreateElement('bar');
   bar.AppendChild(doc.CreateTextNode('me, myself and I'));
   tmp.AppendChild(bar);
   children.AppendChild(tmp);
   // second child
   tmp := doc.CreateElement('child');
   tmp['id'] := '0002';
   foo := doc.CreateElement('foo');
   foo.AppendChild(doc.CreateTextNode('Bob'));
   tmp.AppendChild(foo);
   bar := doc.CreateElement('bar');
   bar.AppendChild(doc.CreateTextNode('blah'));
   tmp.AppendChild(bar);
   children.AppendChild(tmp);
end;

Regards,
Sergei



More information about the Lazarus mailing list