评估XPath相对于上下文节点

huangapple go评论59阅读模式
英文:

Evaluate XPath relative to context node

问题

我正在尝试相对于特定DOM节点评估XPath。也就是说,我想使用表达式 //a 访问 /html/body/div/a,同时指定XPath应该在 <div> 元素上进行评估。

文档来看,似乎 contextNode 参数应该在这里起作用。

<html>
  <body>
    <a href="#">outer</a>
    <div>
      <a href="#">inner</a>
    </div>
  </body>
</html>

我尝试使用 contextNode 参数在 <div> 上评估XPath,但传递它没有效果。我本来希望现在可以找到内部的 <a> 元素。

相反,document.evaluate('//a', div).iterateNext().innerText 返回文本 "outer"。

https://jsfiddle.net/mt04y8db/

英文:

I am trying to evaluate an XPath relative to a particular DOM node. That is, I would like to access /html/body/div/a using the expression //a, while specifying that the XPath should be evaluated on the &lt;div&gt; element.

From the docs, it seems that the contextNode argument should work here.

&lt;html&gt;
  &lt;body&gt;
    &lt;a href=&quot;#&quot;&gt;outer&lt;/a&gt;
    &lt;div&gt;
      &lt;a href=&quot;#&quot;&gt;inner&lt;/a&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;

I tried to evaluate the XPath on the &lt;div&gt; using the contextNode argument, but passing it had no effect. I would have expected that now the inner &lt;a&gt; element should be found.

Instead, document.evaluate(&#39;//a&#39;, div).iterateNext().innerText gives the text "outer".

https://jsfiddle.net/mt04y8db/

答案1

得分: 0

绝对路径以 / 开头,从上下文节点的文档根节点开始搜索,因此可以使用 .//adescendant::a,对于您的示例可能足够简单,只需使用 a

英文:

An absolute path starting with / searches from the document root node (of the context node) so either use .//a or descendant::a, perhaps sufficient for your sample, simply a.

huangapple
  • 本文由 发表于 2023年7月13日 17:53:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定