私は、次のクエリを使用してhtmlテーブルのデータを解析しています。
Dim q = From table In htmldoc.DocumentNode.SelectNodes("//table[@class='Seller']").Cast(Of HtmlNode)()
From row In table.SelectNodes("tr").Cast(Of HtmlNode)()
From header In row.SelectNodes("th").Cast(Of HtmlNode)()
From cell In row.SelectNodes("td").Cast(Of HtmlNode)()
Select New With {Key .Table = table.Id, Key .CellText = cell.InnerText, Key .headerText = header.InnerText}
どのように私は各ループのためにこれをデータテーブルに埋め込むことができます使用することができますか?
私は最初にヘッダーデータを使用して、各ループのネストされたテーブル内のセルデータを埋めるために使用しますが、私は上記のLINQクエリで提案された変更方法もわかりません。
注 :htmlページには常に1つのテーブルしか含まれていません。
与えられたhtml
Dim t = <table class='Seller' id='MyTable'>
<tr>
<th>FooColumn</th>
<td>Foo</td>
<td>Another Foo</td>
</tr>
<tr>
<th>BarColumn</th>
<td>Bar</td>
<td>Another Bar</td>
</tr>
<tr>
<th>ThirdColumn</th>
<td>Third</td>
<td>Another Third</td>
</tr>
</table>
Dim htmldoc = New HtmlAgilityPack.HtmlDocument()
htmldoc.LoadHtml(t.ToString())
あなたの質問
Dim q = From table In htmldoc.DocumentNode.SelectNodes("//table[@class='Seller']")
From row In table.SelectNodes("tr")
From header In row.SelectNodes("th")
From cell In row.SelectNodes("td")
Select New With {.Table = table.Id, .CellText = cell.InnerText, .headerText = header.InnerText}
GroupBy
またはToLookup
を使用して、列ToLookup
にオブジェクトをグループ化できます。
Dim grouped = q.ToLookup(Function(a) a.headerText)
このグループ化を使用して適切なDataColumn
持つDataTable
を作成しDataTable
。
Dim dt = new DataTable()
For Each h in grouped.Select(Function(g) g.Key)
dt.Columns.Add(h)
Next
今度は、 DataTable
を充填するために、各グループには1つの列のデータが含まれているので、グループ化を「回転」させる必要がありDataTable
、各行にデータが必要です。ちょっとヘルパーメソッドを使ってみましょう
Function Rotate(Of T, TR)(source As IEnumerable(Of IEnumerable(Of T)),
selector As Func(Of IEnumerable(Of T), IEnumerable(Of TR))) As IEnumerable(Of IEnumerable(Of TR))
Dim result = new List(Of IEnumerable(Of TR))
Dim enums = source.Select(Function(e) e.GetEnumerator()).ToArray()
While enums.All(Function(e) e.MoveNext())
result.Add(selector(enums.Select(Function(e) e.Current)).ToArray())
End While
Return result
End Function
DataTable
を埋める。
For Each rrow in Rotate(grouped, Function(row) row.Select(Function(e) e.CellText))
dt.Rows.Add(rrow.ToArray())
Next
そして、 DataTable
は次のようになりDataTable
: