Ich habe folgende Tabelle:
<table>
<tr><th>header1</th><th>header2</th><th>header3</th></tr>
<tr><td>value01</td><td>value02</td><td>value03</td></tr>
<tr><td>value11</td><td>value12</td><td>value13</td></tr>
<tr>
<td colspan="3">
<table>
<tr><td>subvalue01</td><td>subvalue02</td></tr>
</table>
</td>
</tr>
</table>
Ich verwende diesen Code, um die Haupttabellenzellenwerte in separaten ArrayList
und Untertabellenzellenwerten in einer anderen ArrayList
zu speichern. Aber meine ArrayList
für Untertabellenzellenwerte speichert die gesamten Werte einschließlich Tabelle und Untertabelle:
foreach (HtmlNode table in hdoc.DocumentNode.SelectNodes("//table"))
{
///This is the table.
foreach (HtmlNode row in table.SelectNodes("tr").Skip(1))
{
///This is the row.
foreach (HtmlNode cell in row.SelectNodes("th|td"))
///can also use "th|td", but right now we ONLY need td
{
//This is the cell.
if (cell.InnerHtml.Contains("<table>"))
{
foreach (HtmlNode subtable in cell.SelectNodes("//table"))
{
foreach (HtmlNode subrow in subtable.SelectNodes("tr").Skip(1))
{
foreach (HtmlNode subcell in subrow.SelectNodes("th|td"))
{
arrSubList.Add(subcell.InnerText);
}
}
}
}
else
{
arrList.Add(cell.InnerText);
}
}
}
}
Was ist falsch an meinem Code?
Ich glaube deine erste Zeile
foreach (HtmlNode table in hdoc.DocumentNode.SelectNodes("//table"))
wählt ALLE Tabellen aus - auf jeder Ebene (einschließlich der verschachtelten Tabellen).
Per: http://www.w3schools.com/XPath/xpath_syntax.asp
// Wählt Knoten im Dokument vom aktuellen Knoten aus, die mit der Auswahl übereinstimmen, unabhängig davon, wo sie sich befinden
Ändern Sie also Ihre erste Zeile zu
foreach (HtmlNode table in hdoc.DocumentNode.SelectNodes("/html/body/table"))
Und sieh, wie das geht.