delphi - 在Delphi中使用XPath查找元素

标签 delphi xpath

我试图在Delphi中的XML文档中找到一个元素。我有这段代码,但是它在日志中总是说0个元素:

function TForm1.KannaSidu: Boolean;
var
  Doc: IXMLDOMDocument; 
  List: IXMLDomNodeList;
begin
  try
    Doc := CreateOleObject('Microsoft.XMLDOM') as IXMLDomDocument;
    Doc.async:=False;
    Doc.load(Filename);
  except
    LogTx('Error on page');
  end;
  List:=Doc.selectNodes('/html/head');
  LogTx(IntToStr(List.length)+' elements');
  Result:=False;
end;


那么,如何使XPath工作呢?

最佳答案

在我在网上找到的selectNodes方法的示例代码中,它前面是通过SelectionNamespaces设置文档的setProperty属性的代码。有些人甚至还设置了SelectionLanguage

Doc.setProperty('SelectionLanguage', 'XPath');
Doc.setProperty('SelectionNamespaces',
  'xmlns:xsl=''http://www.w3.org/1999/XSL/Transform''');


根据您要搜索的元素名称,我想您正在处理HTML文件。基本的HTML元素位于http://www.w3.org/1999/xhtml namespace中,因此请尝试以下操作:

Doc.setProperty('SelectionNamespaces',
  'xmlns:x=''http://www.w3.org/1999/xhtml''');
List := Doc.selectNodes('/x:html/x:head');


也可以看看:

在Microsoft论坛上的selectNodes does not give node list when xmlns is used

关于delphi - 在Delphi中使用XPath查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1406138/

相关文章:

windows - 如何在 Rad Studio xe3 中调试第二个应用程序?

xml - 如何搜索大型 XML 数据集?

java - Java 中的 VTD-XML - 在 XMLModifier.insertAfterElement 之后查找索引

xml - 比较xslt转换上的值

java - 使用 JXPath 查询列表

delphi - 在 DBGrid 中使用 Canvas.TextOut - Delphi XE 3

Delphi IRC 组件

Delphi ADO + 书签

xslt - 为什么 XPath 中的索引从 1 而不是 0 开始?

javascript - 选择没有特定 id、class、xpath 等的元素