我试图在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/