2011-06-15 44 views
7

我有一個XmlDocument包含一個XHTML表。我想遍歷它來處理表格單元格在一次一行,但下面的代碼返回所有單元格嵌套循環,而不是隻爲那些當前行:XPath - 如何選擇節點的子元素?

XmlNodeList tableRows = xdoc.SelectNodes("//tr"); 
foreach (XmlElement tableRow in tableRows) 
{ 
    XmlNodeList tableCells = tableRow.SelectNodes("//td"); 
    foreach (XmlElement tableCell in tableCells) 
    { 
     // this loops through all the table cells in the XmlDocument, 
     // instead of just the table cells in the current row 
    } 
} 

上午什麼我做錯了?謝謝

回答

13

用「。」開始內部路徑。以表示您希望從當前節點開始。即使您在子節點上指定它,也會從xml文檔的根目錄開始搜索「/」總是

所以:

XmlNodeList tableCells = tableRow.SelectNodes(".//td"); 

甚至

XmlNodeList tableCells = tableRow.SelectNodes("./td"); 

那些<td>小號可能是直接根據該<tr>

+0

謝謝,它修復了它。 – Nick 2011-06-15 15:09:39