如何在两个标签之间选择元素

时间:2011-11-02 22:45:40

标签: xpath

  

可能重复:
  xpath select elements between two nodes

基于这个html我需要两个xpath表达式:

<table dir = "rtl .......">
<tbody>
<script src = "get.aspx?type=js&file=ajax&rev=3"......>
<script language = "JavaScript" src = "get.aspx?type=js&file=mc&rev=6"></script>
<script>..</script>
<tr>
<td class = "d2"...>..</td>
</tr>
<tr>..</tr> <--
<tr>..</tr> <--
<tr>..</tr> <-- first expression should select these elements
<tr>..</tr> <--
<tr>..</tr> <--
<tr>..</tr> <--
<tr>..</tr> <--
<tr>
<td class = "d2"...>..</td>
</tr>
<tr>..</tr> <--
<tr>..</tr> <--
<tr>..</tr> <-- second expression should select these elements
<tr>..</tr> <--
<tr>..</tr> <--
<tr>..</tr> <--
<tr>..</tr> <--
</tbody>

如何在带有xpath表达式的第一个<tr>标记之后选择所有<td class = "d2"...>元素,并在第二个<tr>标记之后选择所有<td class = "d2"...>元素和其他xpath表达式。< / p>

1 个答案:

答案 0 :(得分:0)

您可以在XPath 2.0中采用两个节点序列的交集,如此

//table/tbody/tr[td/@class = 'd2'][1]/following-sibling::tr except //table/tbody/tr[td/@class = 'd2'][2]/following-sibling::tr

在该表达式中,您将获得包含类d2的第一个td的tr之后的所有tr兄弟,然后删除那些在第二个这样的tr之后的那些。

不幸的是,XPath 1.0没有两个节点集交集的概念。但是,您可以在XPath 1.0中获取两个节点集的联合:如下所示:

//table/tbody/tr[td/@class = 'd2'][1]/following-sibling::tr | //table/tbody/tr[td/@class = 'd2'][2]/preceding-sibling::tr

以下路径将在包含类d2

的td的第二个tr之后获取tr节点
//table/tbody/tr[td/@class = 'd2'][2]/following-sibling::tr