19

在 Delphi XE 中是否可以将 XPath 与TXmlDocument组件一起使用?

我知道我可以使用后期绑定来访问 MSXML2,然后使用 XPath:

XML := CreateOleObject('MSXML2.DOMDocument.3.0') ;
XML.async := false;
XML.SetProperty('SelectionLanguage','XPath');

但我想知道是否TXmlDocument安装了 Delphi XE 支持 XPath。

4

1 回答 1

15

我在 TXMLDocument 文档中找不到有关 XPath 的任何内容。

XML 示例,来自 OmniXML XPath 演示:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book>
    <title lang="eng">Harry Potter</title>
  </book>
  <book>
    <title lang="eng">Learning XML</title>
  </book>
  <book>
    <title lang="slo">Z OmniXML v lepso prihodnost</title>
    <year>2006</year>
  </book>
  <book>
    <title>Kwe sona standwa sam</title>
  </book>
</bookstore>

尝试这样的事情:

uses 
  XMLDoc, XMLDom, XMLIntf;

// From a post in Embarcadero's Delphi XML forum.
function selectNode(xnRoot: IXmlNode; const nodePath: WideString): IXmlNode;
var
  intfSelect : IDomNodeSelect;
  dnResult : IDomNode;
  intfDocAccess : IXmlDocumentAccess;
  doc: TXmlDocument;
begin
  Result := nil;
  if not Assigned(xnRoot) or not Supports(xnRoot.DOMNode, IDomNodeSelect, intfSelect) then
    Exit;
  dnResult := intfSelect.selectNode(nodePath);
  if Assigned(dnResult) then
  begin
    if Supports(xnRoot.OwnerDocument, IXmlDocumentAccess, intfDocAccess) then
      doc := intfDocAccess.DocumentObject
    else
      doc := nil;
    Result := TXmlNode.Create(dnResult, nil, doc);
  end;
end;


var
  IDoc: IXMLDocument;
  INode: IXMLNode;
begin
  IDoc := LoadXMLDocument('.\books.xml');
  INode := SelectNode(IDoc.DocumentElement,'/bookstore/book[2]/title'); 
end;

就像给其他人的 FYI 一样,我将把它留在:OmniXML支持 XPath,并且有一个演示很好地展示了如何使用它。它也是免费的,带有源代码,支持 Unicode,并且通过它的论坛获得了很好的支持。

于 2011-03-21T21:54:13.437 回答