【问题标题】:XPath and TXmlDocumentXPath 和 TXmlDocument
【发布时间】:2011-07-20 00:39:55
【问题描述】:

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

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

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

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

【问题讨论】:

  • +1 提出一个好问题;事实证明,找到答案比我预期的要难。

标签: delphi xpath delphi-xe txmldocument


【解决方案1】:

我在 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;

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

【讨论】:

  • Ken,非常感谢您的建议,但现在,我只想知道是否可以使用TXMLDocument XPath,避免使用第三方组件。 ;)
  • @Salvador:好的,如果你坚持的话。 :)
  • 那么我们如何设置搜索命名空间呢?即 setProperty('SelectionNamespaces', SearchNS);
  • @Robbie,我不确定。恐怕我不需要这样做。您应该将此作为您自己的新问题发布;您始终可以将此答案作为背景引用(通过右键单击答案下方的share 并复制链接位置来使用可用的链接)。
  • 注意:关于该主题的新问题:stackoverflow.com/questions/30687619/…
猜你喜欢
  • 2015-08-21
  • 2012-03-06
  • 2012-10-05
  • 2013-06-13
  • 1970-01-01
  • 2010-09-25
  • 1970-01-01
  • 2012-06-02
  • 2017-07-01
相关资源
最近更新 更多