我是delphi新手,现在我必须阅读create an xml。我的代码如下:
function foo.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;
sl.Assign(res.XML);// sl is empty after this assignment
//add more elements
generateDOM(rootNode);
Result := res;
end;
问题是,子节点的数量增加了,但 res.XML 为空。更不用说generateDOM 过程中的其余元素似乎没有做任何事情。我将非常高兴得到你的帮助。
免责声明:使用 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 变量,只需使用结果即可。
- 您不需要额外的 StringList 来查看 XML:Result.Xml.Text
- 别忘了Freesl StringList(如果您创建了一个)。
- 您返回的 XmlDocument 在函数之外无法使用,如果您尝试,则会给出 AV.
Why?
这是因为 XMLDocument 旨在用作具有所有者的组件,或作为界面否则,为了管理其lifetime.
事实上,您使用接口来保存根节点会导致它在 Create XmlDocument 函数结束时被销毁。如果你看一下代码TXMLNode._Release
,你会看到它触发了TXMLDocument._Release
除非有 XMLDocument 的所有者(或持有对其引用的接口),否则它会调用 Destroy。
这就是为什么 XMLDocument 有效并填充在 CreateXMLDocument 函数内,但是除非您返回接口或提供所有者,否则在外部不可用.
See the 下面的替代解决方案:
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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)