问题
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:
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.You need to take first node after selecting, so you need to take node with index
0not1
This 2 points will solve your problem, but there are some improvements you can do
- Instead of
SelecNodes().First()you can userSelectSingleNode() - 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