如何在XPath中选择具有特定类的最后一个XHTML <span>元素?</span>

时间:2010-12-27 13:48:06

标签: html xml xhtml xpath

我的目标XHTML文档(简化)如下所示:

<html>
<head>
</head>
<body>
<span class="boris"> </span>
<span class="boris"> </span>
<span class="johnson"> </span>
</body>
</html>

我正在尝试选择最后一堂课“鲍里斯”。

XPath表达式

//span[@class="boris"]

选择所有类型的boris。如何选择最后一个?

我试过

//span[@class="boris" and last()]

这不起作用,因为last()在这里指的是整个文档中的最后一个跨度。

如何选择类boris的所有跨度...然后选择最后一个?

我已经阅读了5或6个XPath教程并完成了大量的Google搜索,我无法单独在XPath中找到解决方法:(

提前感谢您的帮助:)

2 个答案:

答案 0 :(得分:3)

(//span[@class="boris"])[last()]

必须让last()以你想要的方式工作。这样:

//span[@class="boris"][last()]

是错误的,因为它会选择多个<span class="boris">,如果它们是他们父母中的最后一个:

<div>
  <span class="boris">#1</span><!-- this one -->
</div>
<div>
  <span class="boris">#2</span><!-- this one not -->
  <span class="boris">#3</span><!-- but this -->
</div>
<div>
  <span class="boris">#4</span><!-- and this, too -->
  <span class="other">#5</span><!-- this not -->
</div>

第一个表达式只选择一个:#4。这是你需要的。

第二个表达式选择#1,#3和#4,如图所示。


您的尝试(//span[@class="boris" and last()])会选择每个 <span class="boris">,但主要是因为您错了:last()评估为一个数字。除0之外的任何数字在布尔上下文中求值为true。这意味着false的表达式永远不会是<span class="boris">

你必须对布尔值做一个正确的比较:意味着什么

//span[@class="boris" and position() = last()]
但是,这仍然是错误的。它选择#1和#3,因为此处position()last()都在父元素内计数。

当您使用()个parens时,您可以创建一个新的临时节点集,last()可以使用它。

答案 1 :(得分:0)

在这里猜测,但不是//span[@class="boris"][last()]

编辑:

我刚看到你也可以嵌套谓词(见here),所以也许你可以这样做://span[@class="boris"[last()]]

编辑2:

不,这不起作用。跟第一个一起去。顺便说一句,我在网上尝试了你的and last(),它似乎做了你想要的。咦。

相关问题