我如何选择第一个和第二个 h2 之间的所有内容(所有可能的节点)?它们之间可以有n个节点,可以有m个h2标签。
节点不一定要包含在 HTML 元素中,因此选择器可以将它们全部抓取。
<html>
<h2>asdf</h2>
<p>good stuff 1</p>
<p>good stuff 2</p>
<p>good <a href="#">asdf</a>stuff n...</p>
<h2>qwer</h2>
<p>test2</p>
<h2>dfgh</h2>
<p>test2</p>
</html>
我刚刚接触 XPath。请帮助我的新手问题:)
非常感谢!
最佳答案
一个选择所需元素的 XPath 表达式是:
/*/h2[1]
/following-sibling::p
[count(. | /*/h2[2]/preceding-sibling::p)
=
count(/*/h2[2]/preceding-sibling::p)
]
通常,在这种情况下,可以使用 Kayessian 公式求集交集:
$ns1[count(.|$ns2) = count($ns2)]
此 XPath 表达式选择属于两者 节点集的所有节点 $ns1
和 $ns2
.
如果要获取两个给定节点 $n1 和 $n2 之间的所有节点,这是两个节点集的交集:$n1/following-sibling::node()
和 $n2/preceding-sibling::node()
.
只需将这些表达式代入 Kayessian 公式即可得到所需的 XPath 表达式。
在 XPath 2.0 中,当然,我们会使用 <<
或 >>
运算符,类似于:
/*/h2[1]/following-sibling::p[. << /*/h2[1]/]
关于c# - 如何使用 XPath 选择两个节点之间的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9525239/