在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'.