获取NodeCollections中的所有元素 [英] Get all elements in a NodeCollections

查看:98
本文介绍了获取NodeCollections中的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html文件:

I have an html file :

<div class="form-wrapper">
<div></div>
<div class="Clearfix">
<div></div>
<div></div>
<span></span><span class="time">Time</span>
</div>
<div></div>
<div class="Clearfix">
<div></div>
<div></div>
<span></span><span class="time">Time1</span>
</div>
<div></div>
<div class="Clearfix">
<div></div>
<div></div>
<span></span><span class="time">Time2</span>
</div><div></div>
<div class="Clearfix">
<div></div>
<div></div>
<span></span><span class="time">Time3</span>
</div>

我正在使用下面的c#代码来获取所有times项:

I'm using the c# code below to get all the times items :

var node_1 = htmlDocument.DocumentNode.SelectNodes("//div[@class='form-wrapper']").First();
var ITEM = node_1.SelectNodes("//div[@class='clearfix']");
for (int Node = 0; Node < ITEM.Count; Node++)
{
  Console.WriteLine(ITEM[Node].SelectNodes("//span[@class='time']")[1].InnerText.Trim());
}
Console.ReadKey();

我正在使用First()包装纸",因为它们很多.

I'm taking the First() "Form-wrapper" since they're many .

我也尝试使用它:

foreach (var Node in node_1.SelectNodes("//div[@class='clearfix']"))
{
 //
}

问题:如您所见,我有4个Clearfix类,因此我需要获取结果:

Issue is : as you can see I have 4 Clearfix Classes so i need to get the result :

Time
Time1
Time2
Time3

但是由于某些原因,我只能得到:

but for some reasons i only get :

Time
Time
Time
Time

推荐答案

  1. 在某个节点上查询时,一开始不需要//,如果要添加它,查询将在整个文档上执行.

  1. When you are querying over some node you don't need // at the beginning, if you are adding it query will be executed over whole document.

选择后需要获取第一个节点,因此需要获取索引为0而不是1

You need to take first node after selecting, so you need to take node with index 0 not 1

这2点可以解决您的问题,但是您可以做一些改进

This 2 points will solve your problem, but there are some improvements you can do

  1. 您可以使用SelectSingleNode()
  2. 代替SelecNodes().First()
  3. 如果您不需要有关父节点的任何信息,则可以直接查询 对于子节点-htmlDocument.SelectNodes("\\span[@class='time']")将完成所有工作
  1. Instead of SelecNodes().First() you can user SelectSingleNode()
  2. If you don't need any information about parent nodes you can directly query for child nodes - htmlDocument.SelectNodes("\\span[@class='time']") will do all the work

这篇关于获取NodeCollections中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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