简体   繁体   English

select 的父节点如何与 XPath?

[英]How select a parent node with XPath?

If I have如果我有

<div>
  <a>
    <table>
      <tr>
        <td value="val">

If I want to select the a containing a td with value="val" , how can I do that?如果我想 select 包含一个带有value="val"td ,我该怎么做?

I have tested:我已经测试过:

//td[@value="val"]

But I obtain the td node, I want to obtain the a node.但是我获得了td节点,我想获得a节点。 How can I achieve that with XPath?如何使用 XPath 实现这一目标?

You can use either of the below options.您可以使用以下任一选项。

//td[@value="val"]/ancestor::a
^
td with value val
                   ^
                    ancestor link

or或者

Preferred xpath in this case本例首选 xpath

//a[.//td[@value="val"]]
^
Get me any link which have td with value as val.

or或者

The below xpath works now, but when there any change to the page eg: if table is moved into a div, then this xpath will break.下面的 xpath 现在可以工作,但是当页面有任何更改时,例如:如果将表格移动到 div 中,那么这个 xpath 将中断。

//td[@value="val"]/parent::tr/parent::table/parent::a

Personally I prefer the 2nd option atleast in this case as a does not have any specific properties.在这种情况下,我个人更喜欢至少第二个选项,因为a没有任何特定属性。 And ancestor::a will select any link which is ancestor of the td.ancestor::a将 select 任何作为 td 祖先的链接。

The direct answer to your question about how to select a parent in XPath is to use the parent:: axis or the .. abbreviation.关于如何在 XPath 中将 select 作为父级的问题的直接答案是使用parent::轴或..缩写。 However, often, as in your case, you can select the targeted "parent" directly via a predicate on a descendant rather than selecting the descendant and then having to traverse back up to the parent.但是,通常,就像您的情况一样,您可以直接通过后代上的谓词 select 目标“父级”,而不是选择后代然后必须遍历到父级。 For example, ...例如, ...

This XPath,此 XPath,

//a[.//td/@value = "val"]

will select all a elements with a td descendant with a @value attribute value equal to "val" .将 select 所有a td后代且@value属性值等于"val"的元素。


Update: I wasn't paying attention and now see that @suppurtui already provided the above XPath as an option.更新:我没有注意,现在看到@suppurtui 已经提供了上述 XPath 作为选项。 I'll leave this up for any benefit provided by my explanation, but please upvote @supputuri's answer (as I have just done).为了我的解释所提供的任何好处,我将保留此内容,但请支持@supputuri 的回答(正如我刚刚所做的那样)。 Thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM