Delphi - TXMLDocument, created at runtime, generates AV, works with a component in the form

I create an instance of TXMLDocument at run time to load and parse the XML file. You can check the code below:

unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, xmldom, XMLIntf, msxmldom, XMLDoc, StdCtrls; type Txml = class(TForm) // XMLDocument1: TXMLDocument; Memo1: TMemo; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var xml: Txml; implementation {$R *.dfm} procedure Txml.FormCreate(Sender: TObject); var i,j:integer; aNode:IXMLNode; ws:String; XMLDocument1:TXMLDocument; begin Memo1.Lines.Clear; XMLDocument1 := TXMLDocument.Create(nil); try XMLDocument1.LoadFromFile('C:\a.xml'); XMLDocument1.Active := true; aNode := XMLDocument1.ChildNodes.First; while aNode<>nil do begin for i := 0 to aNode.ChildNodes.Count-1 do begin if aNode.ChildNodes[i].NodeName = 'Role' then begin Memo1.Lines.Add('Tag - '+aNode.ChildNodes[i].ChildNodes['Tag'].Text); for j := 0 to aNode.ChildNodes[i].ChildNodes.Count-1 do if aNode.ChildNodes[i].ChildNodes[j].HasChildNodes then begin ws := VarToStr(aNode.ChildNodes[i].ChildNodes[j].ChildValues['Tag']); if trim(ws)<>'' then Memo1.Lines.Add(ws); ws := VarToStr(aNode.ChildNodes[i].ChildNodes[j].ChildValues['Value']); if trim(ws)<>'' then Memo1.Lines.Add(ws); end; end; end; aNode := aNode.NextSibling; end; XMLDocument1.Active := false; finally FreeAndNil(XMLDocument1); end; end; end. 

The problem is that it generates AV. As you probably saw before the component was in the form (// XMLDocument1: TXMLDocument;).

Why, when the component was in the form, the code worked, but when I create it at runtime, it generates AV?

LE: solution : based on answers / comments and Delphi help:

 XMLDocument1 : IXMLDocument; //not TXMLDocument XMLDocument1 := LoadXMLDocument(...); FreeAndNil;// must be deleted 
+7
source share
2 answers

From what I know, you should use the IDoc: IXMLDocument; interface IDoc: IXMLDocument; .

From the docs:

When a TXMLDocument is created without an owner, it behaves like a conjugate object. That is, when all references to its interface are released, an instance of TXMLDocument is automatically freed. when a TXMLDocument is created with the Owner, however, it behaves like any other component and is freed by its owner.

In other words, when creating an instance of TXMLDocument with the owner nil do not call Free() or FreeAndNil() on the instance, but must assign the object to IXMLDocument , so its current reference count is properly managed.

+14
source

You need to tell Owner before the TXMLDocument when creating it at runtime.

 XMLDocument1 := TXMLDocument.Create(xml); 
+2
source

Source: https://habr.com/ru/post/903184/


All Articles