2013-09-10 35 views
0

我有一個HtmlNodeCollection,它使用HTMLAgilityPack從表中收集到的HTML <td>元素。通常情況下,我只需選擇表中的<tr>元素,然後遍歷<td>元素,但不幸的是,<tr>開始標記是通過JavaScript生成的,並且不是從服務器呈現的。我無法控制HTML的呈現方式。因此,我已經使出從這個XPath查詢得到一個HtmlNodeCollection:通過​​循環遍歷​​元素並定義行/列

HtmlNode table = htmlDoc.DocumentNode.SelectSingleNode("//table[@width='100%' and @cellpadding='1' and @cellspacing='1' and @border='0']"); 
HtmlNodeCollection tds = table.SelectNodes(".//td[@align and string-length(@width)=0]"); // only select td elements that have the align attribute and don't have a width attribute 

在該表中,有6列任意數量的行。我想處理每個單獨的行並將列解析爲中間數據結構。我有獲取每個「行」和「列」這個代碼,但它是不完全正確:

int cols = 6; // six columns 
int rows = tds.Count/cols; 

// loop through the rows 
for (int row = 1; row <= rows; row++) 
{ 
    for (int col = 0; col < cols; col++) 
    { 
     HtmlNode td = tds[col * row]; // get the associated td element from the column index * row index 
     MessageBox.Show(td.InnerHtml + "\n" + td.InnerText); 
    } 
} 

我的,而不是在該行0行和結束1行開始算,因爲我不想要六次乘以零。我試圖把它當作矩陣處理,但是我無法定義一行結束和下一行何時開始。你有關於如何正確循環遍歷所有行和列的建議嗎?

回答

0

在紙上繪製出一個網格後,我很清楚我錯過了什麼。我需要將列索引添加到列數乘以當前行像這樣:

for (int row = 0; row < rows; row++) 
{ 
    for (int col = 0; col < cols; col++) 
    { 
     HtmlNode td = tds[col + cols * row]; // get the associated td element from the column index * row index 
     MessageBox.Show(td.InnerHtml + "\n" + td.InnerText); 
    } 
}