XPath and TXmlDocument

19
在Delphi XE中,是否可以使用TXmlDocument组件来使用XPath? 我知道可以使用Late Binding访问MSXML2,然后使用XPath。
XML := CreateOleObject('MSXML2.DOMDocument.3.0') ;
XML.async := false;
XML.SetProperty('SelectionLanguage','XPath');

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


2
这是一个好问题,我发现找到答案比我预期的要困难。 - Ken White
1个回答

15

我在TXMLDocument文档中找不到与XPath相关的内容。

以下是OmniXML XPath演示中的XML示例:

<?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;

仅供其他人参考,我会将这个链接放在这里:OmniXML支持XPath,并提供了一个演示非常好的示例,展示如何使用它。它也是免费的,带有源代码,支持Unicode,并且通过其论坛具有相当好的支持。


Ken,非常感谢您的建议,但现在我只想知道是否可以使用TXMLDocumentXPath,避免使用第三方组件。 ;) - Salvador
@Salvador:好的,如果你坚持的话。 :) - Ken White
那么我们如何设置搜索命名空间呢?例如,设置setProperty('SelectionNamespaces', SearchNS)。 - Robbie Matthews
@Robbie,我不确定。恐怕我没有需要这样做的经验。你应该将这个问题发布为自己的新问题;你总是可以引用这个答案作为背景(使用右键单击下面的“分享”并复制链接位置可用的链接)。 - Ken White
请注意:在该主题上提出了新问题:https://dev59.com/RYvda4cB1Zd3GeqPc7IH - Jerry Dodge
OmniXML对XPath的支持非常有限。即使是简单的X<>Y条件,我也不得不修补库。Kluug的OXML网站对Delphi的一些不同XML库进行了速度测试,因此可能是探索替代方案的起点。 - Arioch 'The

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接