Delphi: EInvalidPointer when trying to access XMLDocument

2.3k views Asked by At

The following code throws an "InvalidPointer" exception everytime I try to access the document's root with XMLDocument.DocumentElement;.

    begin
      XMLDocument := TXMLDocument.Create(nil); // nil since we don't need an owner
      AStream := TStream.Create;  // stream for output as string
      XMLDocument.loadFromXML(xml);// load string
      if NOT (XMLDocument.IsEmptyDoc) then
       begin      
        XMLDocument.Active := true; // actually automatically done by 'loadFromXML'

        // get document root
        HeadNode := XMLDocument.DocumentElement;

        // add <id>-element, set ID as text
        idNode := HeadNode.AddChild(XML_ID_PLAIN);
        idNode.Text := id;

        // ...
     end;
    end;

The string "xml" passed to loadFromXML(string) is valid XML, but the XMLDocument's properties "XML" and "DOMDocument" are always nil, even though neither the object itself nor its "IsEmptyDoc" properties are. Delphi Version is still 2007.

Has anyone an idea what causes this? Thanks in advance.

1

There are 1 answers

0
TLama On BEST ANSWER

Note that this won't answer your question why happens what you've described, but tries to offer you the correct way to do, what you want. Use the LoadXMLData function instead of creating TXMLDocument instance by yourself. Here's a sample code:

uses
  XMLIntf, XMLDoc;

const
  XMLString =
    '<?xml version="1.0" encoding="UTF-8"?>' +
    '<Setup>' +
    '  <FirstNode>First Node Value</FirstNode>' +
    '  <SecondNode>Second Node Value</SecondNode>' +
    '</Setup>';

procedure TForm1.Button1Click(Sender: TObject);
var
  HeadNode: IXMLNode;
  XMLDocument: IXMLDocument;
begin
  try
    XMLDocument := LoadXMLData(XMLString);
    HeadNode := XMLDocument.DocumentElement;
    if Assigned(HeadNode) then
      ShowMessage(HeadNode.NodeName);
  except
    on E: Exception do
      ShowMessage(E.Message);
  end;
end;