Get all elements in a NodeCollections

点点圈 提交于 2020-01-07 03:49:10

问题


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>

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();

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

I tried to use this too :

foreach (var Node in node_1.SelectNodes("//div[@class='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.

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

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

  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


来源:https://stackoverflow.com/questions/43573640/get-all-elements-in-a-nodecollections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!