gpt4 book ai didi

Delphi - 在运行时创建的 TXMLDocument 生成 AV,表单上的组件正在运行

转载 作者:行者123 更新时间:2023-12-03 14:46:02 25 4
gpt4 key购买 nike

我正在运行时创建 TXMLDocument 的实例,以加载和解析 XML 文件。您可以检查以下代码:

    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.

问题是这正在生成 AV。正如您可能已经看到的,在组件出现在表单上之前 (//XMLDocument1: TXMLDocument;)。

为什么当组件位于表单上时代码可以工作,但是当我在运行时创建它时它会生成 AV?

LE:解决方案:基于答案/评论和Delphi帮助:

XMLDocument1 : IXMLDocument;  //not TXMLDocument

XMLDocument1 := LoadXMLDocument(...);

FreeAndNil;// must be deleted

最佳答案

据我所知,您应该改用接口(interface)IDoc: IXMLDocument;

来自文档:

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

换句话说,当创建具有 nil 所有者的 TXMLDocument 实例时,不要调用 Free() 或实例上的 FreeAndNil(),并且您必须将对象分配给 IXMLDocument 变量,以便正确管理其当前事件的引用计数.

关于Delphi - 在运行时创建的 TXMLDocument 生成 AV,表单上的组件正在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8398703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com