XPath - 如何选择节点的子元素?

Nic*_*ick 10 c# xpath

我有一个包含XHTML表的XmlDocument.我想循环遍历它以一次处理一行表格单元格,但下面的代码返回嵌套循环中的所有单元格而不仅仅是当前行的单元格:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?谢谢

Han*_*ing 15

用"."开始内部路径.表示您想要从当前节点开始.起始"/" 始终从xml文档的根目录进行搜索,即使您在子节点上指定它也是如此.

所以:

XmlNodeList tableCells = tableRow.SelectNodes(".//td");
Run Code Online (Sandbox Code Playgroud)

甚至

XmlNodeList tableCells = tableRow.SelectNodes("./td");
Run Code Online (Sandbox Code Playgroud)

因为那些<td>可能就在那之下<tr>.