//p[not(ancestor::*[3])]
//table[ancestor::*[1][self::p] or ancestor::*[2][self::p]]
tr/td//a[ancestor::*[1`][self::td] or ancestor::*[2][self::td]]发布于 2011-01-01 00:53:06
// # from the root node, look at all descendants
p[ # select nodes of type <p>, who have…
not(ancestor::*[3]) # …no ancestor 3 levels up
] #
// # from these nodes, select descendants
table[ # of type <table>, who have…
ancestor::*[1][self::p] # …a <p> as their direct ancestor
or # or
ancestor::*[2][self::p] # …a <p> as their second ancestor
] #
# syntax error, this should be a location step
tr # …select all nodes of type <tr>
/ # from their children…
td # …select all nodes of type <td>
// # from their descendants…
a[ # …select all nodes of type <a>, who have
ancestor::*[1][self::td] # …a <td> as their direct ancestor
or # or
ancestor::*[2][self::td] # …a <td> as their second ancestor
]或者,用HTML表示:
<html>
<body>
<p>
<table>
<tr>
<td>
<a title="These would be selected." />
</td>
</tr>
</table>
</p>
</body>
</html>无论如何,整个XPath没有太多意义。不用说,<p><table>是无效的HTML。
发布于 2011-01-01 00:44:48
让我们将其分解:
//p[not(ancestor::*[3])]选择没有第三个祖先的所有p标记。
在这些文件中:
//table[ancestor::*[1][self::p] or ancestor::*[2][self::p]]它选择第一个或第二个祖先是p标签的所有table标签。
然后:
tr/td//a[ancestor::*[1`][self::td] or ancestor::*[2][self::td]]这并不完全正确(开头应该有一个/ )。但是,它沿着tr/td//向下走,以选择第一个或第二个祖先是a标签的所有td标签。
总而言之,这是非常复杂的,使用在相关位置定义的一些id属性可能更容易实现。
发布于 2011-01-01 02:08:23
您指定的XPath表达式:
//p[not(ancestor::*[3])]
//table[ancestor::*[1][self::p] or ancestor::*[2][self::p]]
tr/td//a在语法上是不合法的--它在tr之前缺少一个/。
修正后的XPath表达式
//p[not(ancestor::*[3])]
//table[ancestor::*[1][self::p] or ancestor::*[2][self::p]]
/tr/td//a是作为 answer 的答案提供的。
正如上面链接的答案中所解释的,其含义是:
这将选择父元素或祖父元素为td、父元素为tr、父元素为表、父元素或祖元素为少于3个ancesstor -element的p的所有a元素
OP想要一种方法来获取a元素,这些元素可以位于一个埋在文档根下面不超过3层的p下,然后位于一个table/tr/td下,其中table被埋在离p不超过3层的地方。
当然,想要选择这样的节点可能看起来不太有意义,,但我们无法判断任何人的需求和要求。
令人惊讶的事实是,XPath是如此强大,甚至可以满足这样的要求。
https://stackoverflow.com/questions/4571169
复制相似问题