HTML XPath - 如何根据每个索引的子值选择节点? [英] HTML XPath - How to select a node based on children's value per index?

查看:27
本文介绍了HTML XPath - 如何根据每个索引的子值选择节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下示例 HTML 代码:

Given the following example HTML code:

<table>
   <tr>
      <td>
         <div>Value 1</div>
      </td>
      <td>
         <div>Value A</div>
      </td>
   </tr>
   <tr>
      <td>
         <div>Value 1</div>
      </td>
      <td>
        <div>Value B</div>
      </td>
   </tr>
   <tr>
      <td>
         <div>Value A</div>
      </td>
      <td>
         <div>Value 1</div>
      </td>
   </tr>
</table>

是否可以编写一个xpath表达式来选择第一列div中具有Value 1"和第二列div中具有Value 2"的(tr)元素柱子?在这个例子中,我只想要第一行.

Is it possible to write a xpath expression to select the (tr) element which has "Value 1" in the div of the first column and "Value 2" in the div of the second column? In this example, I would want only the first row.

如果我检索所有具有值 1"的后代的行,我将获得所有 3 行.

If I retrieve all rows which have descendents with "Value 1" I will get all 3 rows.

如果我检索所有具有Value 1"和Value A"后代的行,我将得到第 1 行和第 3 行.

If I retrieve all rows which have descendents with "Value 1" and "Value A" I will get rows 1 and 3.

重要的不仅是价值,还有顺序.此外,在我的实际情况中,有几列,我需要检查的列可能不是并排的.(例如,可能是我需要检查第 4、7 和 9 列)

It's not only the value that matters, but also the order. Also, in my real case there are several columns and the ones I need to check may not be side by side. (Could be that I need to check columns 4 7 and 9, for example)

我想我正在寻找这样的东西,但它对我不起作用(奇怪的格式是为了可读性,但我相信它仍然有效):

I think I'm looking for something like this, but its not working for me (odd formatting is for readability sake, but I believe its still valid):

//table//tr
[
(.//div[position()=1 and text()='Value 1']) 
and 
(.//div[position()=2 and text()='Value A'])
]

我也试过 [1] 和 [2] 而不是 position() 无济于事.有任何想法吗?谢谢

I've also tried [1] and [2] instead of position() to no avail. Any ideas? Thanks

推荐答案

简单

//tr[normalize-space(td[1]/div) = 'Value 1' and normalize-space(td[2]/div) = 'Value A']

演示 - http://www.xpathtester.com/obj/e3d5b9bf-79d5-4e81-a336-daba38d430fe

这篇关于HTML XPath - 如何根据每个索引的子值选择节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆