声明:经D2007测试。
你的代码确实创建XML(<label/>
)如本修改功能:
function createXMLDocument(): TXMLDocument;
var
res: TXMLDocument;
rootNode: IXMLNode;
sl : TStringList;
begin
res := TXMLDocument.Create(nil);
res.Active := true;
rootNode := res.AddChild('label');
// create string for debug purposes
sl := TStringList.Create; // not needed
sl.Assign(res.XML); // Not true: sl is empty after this assignment
ShowMessage(sl.text);// sl is NOT empty!
sl.Free; // don't forget to free it! use try..finally.. to guarantee it!
//add more elements
// generateDOM(rootNode);
Result := res;
end;
但它要求一个很多言论的:
- 你不需要本地res变量,只需使用Result。
- 你并不需要一个额外的StringList看到XML:Result.Xml.Text
- 如果你创建了一个不要忘记免费的SL的StringList。
- 您返回的XmlDocument在函数外部不可用,并在您尝试使用时提供AV。
为什么?
这是因为一个XMLDocument旨在被用作组分与所有者,或作为接口否则,为了管理其寿命。
您使用接口来保存rootNode的事实会导致它在CreateXmlDocument函数的末尾被销毁。并且,如果您查看TXMLNode._Release
中的代码,则会看到触发器TXMLDocument._Release
会调用Destroy,除非XMLDocument有一个所有者(或拥有对其的引用的接口)。
这就是为什么XMLDocument在CreateXMLDocument函数内有效且填充的情况,但不在外部可用,除非您返回接口或提供所有者。
见替代解决方案如下:
function createXMLDocumentWithOwner(AOwner: TComponent): TXMLDocument;
var
rootNode: IXMLNode;
begin
Assert(AOwner <> nil, 'createXMLDocumentWithOwner cannot accept a nil Owner');
Result := TXMLDocument.Create(AOwner);
Result.Active := True;
rootNode := Result.AddChild('label');
OutputDebugString(PChar(Result.Xml.Text));
//add more elements
// generateDOM(rootNode);
end;
function createXMLDocumentInterface(): IXMLDocument;
var
rootNode: IXMLNode;
begin
Result := TXMLDocument.Create(nil);
Result.Active := True;
rootNode := Result.AddChild('label');
OutputDebugString(PChar(Result.Xml.Text));
//add more elements
// generateDOM(rootNode);
end;
procedure TForm7.Button1Click(Sender: TObject);
var
doc: TXmlDocument;
doc2: IXMLDocument;
begin
ReportMemoryLeaksOnShutdown := True;
doc := createXMLDocument;
// ShowMessage(doc.XML.Text); // cannot use it => AV !!!!
// already freed, cannot call doc.Free;
doc := createXMLDocumentWithOwner(self);
ShowMessage(doc.XML.Text);
doc2 := createXMLDocumentInterface;
ShowMessage(doc2.XML.Text);
end;
将是一件好事,如果你提供你正在使用的德尔福版本。在D2007的情况下查看我的答案。 – 2009-10-08 00:37:11