我在使用delphi 6/7中的TXMLDocument控件解析XML文档时遇到了一些问题:我使用程序创建的方式,而不是拖曳控件来创建XMLDocument对象。
我使用IXMLNODE接口变量访问XML节点。我将对象变量声明为TXMLDocument类的对象,然后在实例化的时候,构造函数的Owner参数使用Nil。之后在解析xml文档的时候就无法定位到任何节点,同时抛出内存访问异常。
然而,如果我使用一个正常的TComponent对象作为Owner传给构造函数(比如窗体的self),这时一切就正常了。开始我以为TXMLDocument.Create(owner)不能提供nil作参数,但是TXMLDocument控件源码中重载的Create(FileName)构造函数本身就是inherited了Create(nil)-------------------------------------------------------
var
  xmlFile: TXMLDocument;
  node : IXMLNode;
begin
  xmlFile:=TXMLDocument.Create(Nil);
  xmlFile.LoadFromFile('config.xml');
  xmlFile.Active := True;
  node := xmlFile.ChildNodes.Nodes['configs'];  //Address violation
......
-------------------------------------------------------  
另一方面,如果我在对象变量声明为IXMLDocument接口变量,然后用TXMLDocument.Create(nil)去实例化它就不会有上述现象,一切正常。-------------------------------------------------------
var
  xmlFile: IXMLDocument;
  node : IXMLNode;
begin
  xmlFile:=TXMLDocument.Create(Nil);
  xmlFile.LoadFromFile('config.xml');
  node := xmlFile.ChildNodes.Nodes['configs'];  //OK
......
-------------------------------------------------------请问各位高手,这是怎么一回事啊?

解决方案 »

  1.   

    抱歉,代码片断2少了一句Active的语句。
      

  2.   

    procedure TForm1.Button1Click(Sender: TObject);
    var
    a: TXMLDocument;
    b:string;
    begin
    a:=TXMLDocument.Create(self);
    a.FileName:='http://localhost/xml/web.xml';
    a.Active:=true;
    b:=a.DocumentElement.ChildNodes['servlet'].ChildNodes['display-name'].Text;
    showmessage(b);
    end;
      

  3.   

    定义时 xmlFile: IXMLDocument;
    node : IXMLNode;要么全定义成IXMLDocument
    要么全定义成TXMLDocument
      

  4.   

    可以参考一下这个的代码:
    http://blog.csdn.net/linzhengqun
    第一篇文章,也可以拿来用哦。
      

  5.   

    谢谢linzhengqun提供的文章,我要好好学习一下。
    请问FlyBird2004,如果定义一个类型变量一个是接口变量,其机制上会有什么障碍吗?谢谢
      

  6.   

    在帮助文档看到这样一段:
    When TXMLDocument is created without an Owner, it behaves like an interfaced object. That is, when all references to its interface are released, the TXMLDocument instance is automatically freed. When TXMLDocument is created with an Owner, however, it behaves like any other component, and is freed by its Owner. When you add a TXMLDocument component from the component palette to a form or data module, it is automatically created with an Owner. When the TXMLDocument component is created using the global LoadXMLDocument function (or by a function that the XML Data Binding wizard generates to return the root node of the document), the function creates a TXMLDocument instance without an Owner.说如果Owner是nil,就相当于声明了一个IXMLDOCUMENT接口变量,那么这个和解析文档的问题有关吗?