我正在用 node.js 构建一个小型文档解析器。为了测试,我有 a raw HTML file ,通常是在应用程序执行时从真实网站下载的。
我想从 Console.WriteLine 的每个部分中提取与我的约束相匹配的 first 代码示例 - 它必须用 C# 编写。为此,我有这个示例 XPath:
//*[@id='System_Console_WriteLine_System_String_System_Object_System_Object_System_Object_']/parent::div/following-sibling::div/pre[position()>1]/code[contains(@class,'lang-csharp')]
如果我test the XPath online ,我得到了预期的结果,is in this Gist .
在我的 node.js 应用程序中,我使用 xmldom和 xpath尝试解析完全相同的信息:
var exampleLookup = `//*[@id='System_Console_WriteLine_System_String_System_Object_System_Object_System_Object_']/parent::div/following-sibling::div/pre[position()>1]/code[contains(@class,'lang-csharp')]`;
var doc = new dom().parseFromString(rawHtmlString, 'text/html');
var sampleNodes = xpath.select(exampleLookup,doc);
但是,这不会返回任何内容。
这里可能发生了什么?
最佳答案
这很可能是由您的 HTML (XHTML) 中的默认命名空间 (xmlns="http://www.w3.org/1999/xhtml"
) 引起的。
查看 xpath docs ,您应该能够使用 useNamespaces
将命名空间绑定(bind)到前缀,并在您的 xpath 中使用该前缀(未经测试)...
var exampleLookup = `//*[@id='System_Console_WriteLine_System_String_System_Object_System_Object_System_Object_']/parent::x:div/following-sibling::x:div/x:pre[position()>1]/x:code[contains(@class,'lang-csharp')]`;
var doc = new dom().parseFromString(rawHtmlString, 'text/html');
var select = xpath.useNamespaces({"x": "http://www.w3.org/1999/xhtml"});
var sampleNodes = xpath.select(exampleLookup,doc);
除了将命名空间绑定(bind)到前缀,您还可以在 XPath 中使用 local-name()
,但我不推荐这样做。这也涵盖了in the docs .
例子...
//*[@id='System_Console_WriteLine_System_String_System_Object_System_Object_System_Object_']/parent::*[local-name()='div']/following-sibling::*[local-name()='div']/*[local-name()='pre'][position()>1]/*[local-name()='code'][contains(@class,'lang-csharp')]
关于javascript - 在 node.js 中使用 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47464357/