在Delphi中使用XPath查找元素 [英] Finding elements with XPath in Delphi

查看:411
本文介绍了在Delphi中使用XPath查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to find an element in an XML document in Delphi. I have this code, but it always says 0 elements in the log:

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工作?

So how do I make XPath work?

推荐答案

如果您只是尝试将普通的html文件加载为xml,则可能有多种原因导致失败并阻塞:

If you're just trying to load a plain html file as xml, it would probably have multiple reasons to fail and choke on things like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

在执行其他操作之前,您必须测试它是否正确加载:

You have to test that it actually loads correctly before doing anything else:

  if not Doc.load(filename) then
    raise Exception.Create('XML Loading error:' + Trim(Doc.parseError.reason));

它将为您提供发生这种故障的具体原因:

It will give you the specific reason for the failure like this one:

XML Loading error:End tag 'head' does not match the start tag 'link'.

这篇关于在Delphi中使用XPath查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆