TXMLDocument 'Invalid pointer operation' when freeing

delphi, delphi-xe2, exception, xml

Solution

It's stated in the `constructor's` reference:

TXMLDocument components that are created at runtime without an owner are freed automatically when all references to their IXMLDocument interface are released.

Since you've specified no `Owner` in your `TXMLDocument` constructor call, you should not release it by yourself.

Problem

I'm using the `TXMLDocument` to write an XML string which is used in a web server. The component is created when the server receives the request, produces XML, passes it back to the client, then the component is free'd. However, when this component is free'd, I get `Invalid pointer operation`. ``` XML:= TXMLDocument.Create(nil); try XML.Active:= True; nRoot:= XML.AddChild('topics'); for X := 0 to FCHM.Topics.Count - 1 do begin nTopic:= nRoot.AddChild('topic'); //Add more data... end; Response.ContentText:= XML.XML.Text; Response.ContentType:= 'text/xml'; XML.Active:= False; finally XML.Free; //<-- Invalid pointer operation end; ``` Why am I getting this and how do I get rid of it? Strangely, although I can confirm that `Response.ContentText` did in fact get the XML, for some reason the web server fails to return this data back to the client after this exception - but I'm assuming that's a different cause/effect issue. PS - `CoInitialize(nil)` and `CoUninitialize` are called around this handler since the web server is multi-threaded and the `TXMLDocument` is COM.

Original source