HTML 테이블 (여기 링크 http://road2paris.com/wp-content/themes/roadtoparis/api/generated_table_august.html )에서 일부 데이터를 가져오고 양식 응용 프로그램의 DataGridView에서 처음 16 명을 표시하려고했습니다. 내가 읽은 가장 좋은 방법은 HTML Agility Pack을 사용하는 것이므로 다운로드하여 프로젝트에 포함시켰다. 가장 먼저해야 할 일은 html 파일의 내용을로드하는 것입니다. 이것은 내가 그렇게하는 데 사용한 코드입니다.
string htmlCode = "";
using (WebClient client = new WebClient())
{
client.Headers.Add(HttpRequestHeader.UserAgent, "AvoidError");
htmlCode = client.DownloadString("http://road2paris.com/wp-content/themes/roadtoparis/api/generated_table_august.html");
}
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlCode);
그리고 나는 붙어있다. 데이터 테이블을 html 테이블의 데이터로 채우는 방법을 모르겠습니다. 많은 다양한 솔루션을 시도했지만 제대로 작동하지 않는 것 같습니다. 누군가 나를 도울 수 있다면 기쁠 것입니다.
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlCode);
var headers = doc.DocumentNode.SelectNodes("//tr/th");
DataTable table = new DataTable();
foreach (HtmlNode header in headers)
table.Columns.Add(header.InnerText); // create columns from th
// select rows with td elements
foreach (var row in doc.DocumentNode.SelectNodes("//tr[td]"))
table.Rows.Add(row.SelectNodes("td").Select(td => td.InnerText).ToArray());
이 코드를 사용하려면 HTML 민첩성 팩 라이브러리가 필요합니다.
아래에는 중복 데이터 헤더가 없도록 코드를 작성했습니다. DataTable을 만들 때 각 "열"은 고유 한 이름을 가져야합니다. 또한 HTML 행이 범위를 벗어날 수 있으며 데이터 테이블에 열을 추가해야하는 경우가 있습니다. 그렇지 않으면 데이터가 삭제됩니다. 이것이 내 해결책이었습니다.
'''
public enum DuplicateHeaderReplacementStrategy
{
AppendAlpha,
AppendNumeric,
Delete
}
public class HtmlServices
{
private static readonly string[] Alpha = new[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
public static HtmlDocument RenameDuplicateHeaders(HtmlDocument doc, DuplicateHeaderReplacementStrategy strategy)
{
var index = 0;
try
{
foreach (HtmlNode table in doc.DocumentNode?.SelectNodes("//table"))
{
var tableHeaders = table.SelectNodes("th")?
.GroupBy(x => x)?
.Where(g => g.Count() > 1)?
.ToList();
tableHeaders?.ForEach(y =>
{
switch (strategy)
{
case DuplicateHeaderReplacementStrategy.AppendNumeric:
y.Key.InnerHtml += index++;
break;
case DuplicateHeaderReplacementStrategy.AppendAlpha:
y.Key.InnerHtml += Alpha[index++];
break;
case DuplicateHeaderReplacementStrategy.Delete:
y.Key.InnerHtml = string.Empty;
break;
}
});
}
return doc;
}
catch
{
return doc;
}
}
}
public static DataTable GetDataTableFromHtmlTable(string url, string[] htmlIds)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(url);
string html = doc.DocumentNode.OuterHtml;
doc = HtmlServices.RenameDuplicateHeaders(doc, DuplicateHeaderReplacementStrategy.AppendNumeric);
var headers = doc.DocumentNode.SelectNodes("//tr/th");
DataTable table = new DataTable();
foreach (HtmlNode header in headers)
if (!table.ColumnExists(header.InnerText))
{
table.Columns.Add(header.InnerText); // create columns from th
}
else
{
int columnIteration = 0;
while (table.ColumnExists(header.InnerText + columnIteration.ToString()))
{
columnIteration++;
}
table.Columns.Add(header.InnerText + columnIteration.ToString()); // create columns from th
}
// select rows with td elements
foreach (var row in doc.DocumentNode.SelectNodes("//tr[td]"))
{
var addRow = row.SelectNodes("td").Select(td => td.InnerHtml.StripHtmlTables()).ToArray();
if (addRow.Count() > table.Columns.Count)
{
int m_numberOfRowsToAdd = addRow.Count() - table.Columns.Count;
for (int i = 0; i < m_numberOfRowsToAdd; i++)
table.Columns.Add($"ExtraColumn {i + 1}");
}
try
{
table.Rows.Add(addRow);
}
catch (Exception e)
{
debug.Print(e.Message);
}
}
return table;
}