通过TXMLDocument访问IXMLDOMDocument2?

时间:2013-06-17 08:57:42

标签: delphi msxml txmldocument

我使用Delphi的TXMLDocument类并使用TransformNode方法执行XSLT转换。

但是,我需要启用XSLT Javascript函数(<msxml:script>标记)和 - 经过大量谷歌搜索 - 这意味着我需要将AllowXsltScript的{​​{1}}属性设置为true。

http://msdn.microsoft.com/en-us/library/windows/desktop/ms760290(v=vs.85).aspx

我已经成功实现了这一目标 - 但只能通过在IXMLDOMDocument2中修改Delphi库函数CreateDOMDocument的来源。

msxmldom.pas

显然这远远不能令人满意 - 那么如何在没有修改库代码的情况下访问IXMLDOMDocument2对象

2 个答案:

答案 0 :(得分:4)

您可以通过MSXMLDOMDocumentCreate变量覆盖创建功能:

unit Unit27;

interface

uses
  xmldoc, xmlintf, msxml, msxmldom, Forms, SysUtils, 
  ActiveX, ComObj, XmlDom, XmlConst,
  Windows, Messages, Classes, Controls, StdCtrls;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function TryObjectCreate(const GuidList: array of TGuid): IUnknown;
var
  I: Integer;
  Status: HResult;
begin
  Status := S_OK;
  for I := Low(GuidList) to High(GuidList) do
  begin
    Status := CoCreateInstance(GuidList[I], nil, CLSCTX_INPROC_SERVER or
      CLSCTX_LOCAL_SERVER, IDispatch, Result);
    if Status = S_OK then Exit;
  end;
  OleCheck(Status);
end;

function CreateDOMDocument2: IXMLDOMDocument;

var
  Doc2 : IXMLDOMDocument2;

begin
  Doc2 := TryObjectCreate([CLASS_DOMDocument60, CLASS_DOMDocument40, CLASS_DOMDocument30,
    CLASS_DOMDocument26, msxml.CLASS_DOMDocument]) as IXMLDOMDocument2;
  if not Assigned(Doc2) then
    raise DOMException.Create(SMSDOMNotInstalled);
  Doc2.setProperty('AllowXsltScript', true);
  Result := Doc2;
end;


procedure TForm1.FormCreate(Sender: TObject);

var
 Doc : IXMLDocument;

begin
 Doc := TXMLDocument.Create(nil);
 Doc.LoadFromFile('c:\temp\test.xml');
end;


initialization
 MSXMLDOMDocumentCreate := CreateDOMDocument2;
end.

答案 1 :(得分:3)

请注意,在XE3及更高版本中,不推荐MSXMLDOMDocumentCreate支持子类化TMSXMLDOMDocumentFactory并覆盖它的CreateDOMDocument函数。供将来参考,以下是XE3和XE4的示例:

interface

type
  TMSXMLDOMDocument2Factory = class(TMSXMLDOMDocumentFactory)
  public
    class function CreateDOMDocument: IXMLDOMDocument; override;
  end;

implementation

{ TMSXMLDOMDocument2Factory }

class function TMSXMLDOMDocument2Factory.CreateDOMDocument: IXMLDOMDocument;
begin
  Result := inherited;
  if not Assigned(Result) then
    raise DOMException.Create(SMSDOMNotInstalled);
  AddDOMProperty('AllowXsltScript', True);
  SetDOMProperties(Result as IXMLDOMDocument2);
end;

initialization
  MSXMLDOMDocumentFactory := TMSXMLDOMDocument2Factory;

end.