什么是正确的 XPath 函数,用于排除节点



>我对 XPath 函数有问题

我只想得到"第一行"和"第四行",但我想用有语句的逻辑来获取它,

第一条语句是我想获得具有类"row1"的节点其次,我想忽略所有具有类"excludeRow"的节点

我已经尝试了not(starts-with)和not(contains(@class,"excludeRow"))函数,但仍然无法得到我想要的。

这是我的例子

<tr><td>"Header"</td></tr>
<tr class="row1"><td>"First Row"</td><tr>
<tr class="excludeRow1"><td>"Second Row"</td></tr>
<tr class="excludeRow2"><td>"Third Row"</td></tr>
<tr><td>"Fourth Row"</td></tr>
<tr class="excludeRow3"><td>"Fifth Row"</td></tr>

这是我最近的代码,希望有人可以纠正或解决这个:D

  1. '//tr[@class="row1" and not(starts-with(@class, 'excludeRow'))]';
  2. '//tr[not(contains(@class, 'excludeRow'))]';

此代码没有错误,但结果与我预期不符

谢谢大家,问候! :D

您应该使用or来选择属性等于"row1"class或者没有以"excludeRow"开头的属性class行。但是,这将包括"标题"行。如果要跳过"标头",请添加另一个条件以跳过第一个tr

//tr[position() > 1][@class='row1' or not(starts-with(@class, 'excludeRow'))]

上面的 XPath 应该返回两个预期的行"第一行"和"第四行"(参见 xpathtester 中的演示)

首先,请注意您使用无效的html,因为第二行没有正确关闭。但是,如果它正确关闭,以下语句应该有效:

  1. //tr[@class="row1"]
  2. //tr[not(contains(@class, "excludeRow")) and not(@class="row1") and not(position()=1)]

第一条语句只是选择类等于 row1 的所有 tr

第二条语句选择在其类属性中不包含 excludeRow 的所有 tr,此外还排除在第一条语句中选择的行。最后,为了排除标题行,它排除了第一个元素。

最新更新