Ich muss nur eine Tabelle in HTML analysieren, die wie folgt aussieht:
<html>
<head>
<title>
</title>
</head>
<body>
<table>
***contents***
</table>
</body>
</html>
Mein Code sieht so aus:
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***
}
}
}
Aber dann bekomme ich NullReferenceException um
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))
Also Tisch hat nichts drin, aber warum?
Ich habe es behoben. Das Problem war die LoadHtml- Methode, die eine HTML-Zeichenfolge als Parameter verwendet. Für eine Datei sollte Load verwendet werden.
Da Sie in Ihrem HTML keine Tabellenzeilen von tr haben, findet das Agilitätspaket keine
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)
{
}