使用 Html Agility Pack,选择循环中的当前元素 (XPATH)
我正在尝试做一些简单的事情,但不知何故它对我不起作用,这是我的代码:
var items = html.DocumentNode.SelectNodes("//div[@class='itembox']");
foreach(HtmlNode e in items)
{
int x = items.count; // equals 10
HtmlNode node = e;
var test = e.SelectNodes("//a[@class='head']");// I need this to return the
// anchor of the current itembox
// but instead it returns the
// anchor of each itembox element
int y =test.count; //also equals 10!! suppose to be only 1
}
我的 html 页面如下所示:
....
<div class="itembox">
<a Class="head" href="one.com">One</a>
</div>
<div class="itembox">
<a Class="head" href="two.com">Two</a>
</div>
<!-- 10 itembox elements-->
....
我的 XPath 表达式错误吗?我错过了什么吗?
I'm trying to do something simple, but somehow it doesnt work for me, here's my code:
var items = html.DocumentNode.SelectNodes("//div[@class='itembox']");
foreach(HtmlNode e in items)
{
int x = items.count; // equals 10
HtmlNode node = e;
var test = e.SelectNodes("//a[@class='head']");// I need this to return the
// anchor of the current itembox
// but instead it returns the
// anchor of each itembox element
int y =test.count; //also equals 10!! suppose to be only 1
}
my html page looks like this:
....
<div class="itembox">
<a Class="head" href="one.com">One</a>
</div>
<div class="itembox">
<a Class="head" href="two.com">Two</a>
</div>
<!-- 10 itembox elements-->
....
Is my XPath expression wrong? am i missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代替使用
。您当前的代码(
//a[]
)搜索从根节点开始的所有 a 元素。如果您用点作为前缀 (.//a[]
),则仅考虑当前节点的后代。由于它是您的情况的直接子代,您当然也可以这样做:一如既往地查看 Xpath 规范
Use
instead. Your current code (
//a[]
) searches all a elements starting from the root node. If you prefix it with a dot instead (.//a[]
) only the descendants of the current node will be considered. Since it is a direct child in your case you could of course also do:As always see the Xpath spec for details.
这是一个绝对表达式,但您需要一个相对 XPath 表达式——要根据
e
进行计算。因此使用:
请注意:尽可能避免使用 XPath
//
伪运算符,因为这样的使用可能会导致显着的低效率(减速)。在这个特定的 XML 文档中,
a
元素只是div
的子元素,而不是位于div
的不确定深度。This is an absolute expression, but you need a relative XPath expression -- to be evaluated off
e
.Therefore use:
Do note: Avoid using the XPath
//
pseudo-operator as much as possible, because such use may result in significant inefficiencies (slowdown).In this particular XML document the
a
elements are just children ofdiv
-- not at undefinite depth offdiv
.