J'ai juste besoin d'analyser un tableau en HTML, qui ressemble à ceci:
<html>
<head>
<title>
</title>
</head>
<body>
<table>
***contents***
</table>
</body>
</html>
Mon code ressemble à ceci:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(@path);
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))
{
foreach (HtmlNode row in table.SelectNodes("tr"))
{
foreach (HtmlNode cell in row.SelectNodes("th|td"))
{
***copy content***
}
}
}
Mais alors je reçois NullReferenceException à
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))
Donc, la table n'a rien dedans, mais pourquoi?
Je l'ai réparé. Le problème était la méthode LoadHtml , qui prend une chaîne HTML en tant que paramètre. Pour un fichier, charge devrait être utilisée.
Comme vous n'avez aucune ligne de table de tr dans votre code HTML, le pack d'agilité n'en trouve aucune
try this
// Get all tables in the document
HtmlNodeCollection tables = doc.DocumentNode.SelectNodes("//table");
// Iterate all rows in the first table
HtmlNodeCollection rows = tables[0].SelectNodes(".//tr");
for (int i = 0; i < rows.Count; ++i)
{
}