Ecco la struttura della tabella:
<table class="tb-stock tb-option">
<tr>
<th class="bgc2">col1</th>
<th class="bgc2">col2</th>
<th class="bgc2">col3</th>
</tr>
<tr class="alt-row">
<th class="">2018/1/29</th>
<td class="">0.11</td>
<td class=" b-b">0.50</td>
</tr>
<tr class="alt-row">
<th class="">2018/1/30</th>
<td class="">0.22</td>
<td class=" b-b">0.55</td>
</tr>
</table>
Voglio ottenere tutti gli elementi sotto "tr" (compresi "th" e "td")
Come posso usare linq per raggiungere questo obiettivo?
I problemi si trovano in "..tr.Elements (" td | th ") .."
codice:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(ms, Encoding.UTF8);
List<List<string>> table =
doc.DocumentNode.SelectSingleNode("//table[@class='tb-stock tb-option']")
.Descendants("tr")
.Skip(1)
.Where(tr => tr.Elements("th").Count() >= 1)
.Select(tr => tr.Elements("td|th").Select(td => td.InnerText).ToList())
.ToList();
È possibile utilizzare il seguente codice per estrarre i testi interni di td o gli elementi I testarlo nel mio locale l'output è:
2018/1/29
0.11
0.50
2018/1/30
0.22
0.55
Puoi filtrare gli elementi in linea:
// both td and th
.Where(node => "td|th".Contains(node.Name))
// only td
.Where(node => "td".Contains(node.Name))
Il codice funzionante è:
HtmlDocument doc = new HtmlDocument();
doc.Load("test.html", Encoding.UTF8);
List<string> table =
doc.DocumentNode.SelectSingleNode("//table[@class='tb-stock tb-option']")
.Descendants("tr")
.Skip(1)
.Where(tr => tr.Elements("th").Count() >= 1)
.SelectMany(tr => tr.ChildNodes)
.Where(node => "td|th".Contains(node.Name))
.Select(node => node.InnerText)
.ToList();
foreach (var str in table)
{
Console.WriteLine(str);
}