1

I have this XML file:

<?xml version="1.0" encoding="UTF-8"?>
<MyApp_Favorites version="1.0">
  <Favorite Path="D:\MyTextA.txt" Page="2"/>
  <Favorite Path="D:\MyTextB.txt" Page="33"/>
  <Favorite Path="D:\MyTextC.txt" Page="1"/>
</MyApp_Favorites>

Now I try to start to read the children of MyApp_Favorites and their respective attributes by starting to read the root node (and then I would try to read the children of the root node):

procedure TFormMain.LoadFavorites;
var
  XMLDoc: TXMLDocument;
  ThisRootNode, ThisFavNode: IXMLNode;
begin
  XMLDoc := TXMLDocument.Create(nil);
  XMLDoc.LoadFromFile('R:\test.xml');
  XMLDoc.Active := True;
  ThisRootNode := XMLDoc.ChildNodes.First;
  CodeSite.Send('ThisRootNode.Text', ThisRootNode.Text);

However, ThisRootNode.Text gives me back:

version="1.0" encoding="UTF-8"

But doesn't the XML specification say that the XML Prolog is not part of the XML document content? So why do I get the XML Prolog as part of the XML document? And how can I get the root node MyApp_Favorites and then its Favorite child nodes with their attributes?

user1580348
  • 5,721
  • 4
  • 43
  • 105
  • 1
    You need to access `XMLDoc.DocumentElement`, not `XMLDoc`. – Ken White Dec 19 '16 at 00:07
  • But with `XMLDoc.DocumentElement.ChildNodes.First` I get an `Invalid pointer operation` error. – user1580348 Dec 19 '16 at 00:21
  • Very strange: When I write `XMLDoc := TXMLDocument.Create(nil);` I get the `invalid pointer operation` error. But when I write `XMLDoc := TXMLDocument.Create(Self);` then there is no error. Why? – user1580348 Dec 19 '16 at 00:33
  • OK, when I use `Self` as the owner of the `TXMLDocument` object instance then everything works as expected and the problem is solved :) I assume that I have to free the `TXMLDocument` object or is automatically freed by the owning form when the form is destroyed? – user1580348 Dec 19 '16 at 01:46
  • 1
    [Read the documentation](http://docwiki.embarcadero.com/Libraries/en/Xml.XMLDoc.TXMLDocument). When you create `TXMLDocument` with a `nil` Owner, it acts as a reference counted interface object, so you need to assign it to an `IXMLDocument` interface variable, not a `TXMLDocument` variable, to maintain the reference counting correctly. In which case, you should use [`LoadXMLDocument()`](http://docwiki.embarcadero.com/Libraries/en/Xml.XMLDoc.LoadXMLDocument) instead of `LoadFromFile()` directly. – Remy Lebeau Dec 19 '16 at 02:19
  • Here we are again at malicious downvoting of my legitimate and well-formulated questions (was +1 before) by some specific people without any explanations! – user1580348 Dec 19 '16 at 22:45

0 Answers0